/*****************************************************************************
 * Copyright (C) 2004-2009 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 package 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 package; if not, write to the Free Software               *
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA *
 *****************************************************************************/

#include "kvpncconfig.h"

#include <QtCore/QRegExp>
#include <QtGui/QCursor>
#include <QtXml/QDomDocument>
#include <QDir>


#include <kconfiggroup.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kpushbutton.h>
#include <kstandarddirs.h>
#include <kurl.h>
#include <kinputdialog.h>
#include <klineedit.h>
#include <unistd.h>
#include <iostream>

#include "kvpncimportprofileselectiondialog.h"
#include "utils.h"

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

    pathToVpnc = "";
    pathToCiscoVpnc = "";
    pathToRacoon = "";
    pathToRacoonctl = "";
    pathToSetkey = "";
    pathToIpsec = "";
    pathToPppd = "";
    pathToPptp = "";
    pathToL2tpd = "";
    pathToXl2tpd = "";
    pathToOpenl2tp = "/usr/sbin/openl2tp";
    pathToKill = "";
    pathToKillall = "";
    pathToPing = "";
    pathToOpenvpn = "/usr/sbin/openvpn";
    pathToIp = "/sbin/ip";
    pathToIfconfig = "/sbin/ifconfig";
    pathToRoute = "/sbin/route";
    pathToNetstat = "/bin/netstat";
    pathToL2tpd = "/usr/sbin/l2tpd";
    pathToPkcs11Tool = "/usr/bin/pkcs11-tool";
    pathToVtund = "/usr/sbin/vtund";
    pathToCiscoCertMgr = "/usr/local/bin/cisco_cert_mgr";
    pathToTail = "/usr/bin/tail";
    pathToSsh = "/usr/bin/ssh";
    pathToKsshAskpass = "/usr/bin/ksshaskpass";
    pathToGnomeSshAskpass = "/usr/lib/openssh/gnome-ssh-askpass";
    AutoConnectProfile = "";
    Vpnc_pid_file = "";
    Pppd_pid_file = "";
    lastProfile = "";
    logfileName = "";
    InterpreterShell = "/bin/bash";

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

    OldDefaultGw = "";
    OldDefaultDev = "";

    connectSleepDelay = 15;
    connectSleepRetry = 0;
    tryConnectTimeout = 10;
    runningCheckCounter = 0;
    runningCheckTimeout = 60;
    mainwindow_pos_x = 0;
    mainwindow_pos_y = 0;
    mainwindow_height = 200;
    mainwindow_width = 400;
    AuthRetryCount = 0;
    PppdKernelLogLevel = 0;
    maxConnectRetry = 3;
    currentConnectRetry = 0;

    OpenvpnManagementPort = 2222;

    minimizeAfterConnect = true;
    //showDebugConsole = false;
    useDefaultPaths = false;
    writeLogFile = true;
    useSilentQuit = false;
    holdGeneratedScripts = true;
    enableDebugPppd = false;
    enableDebugPptpd = false;
    enableDebugL2tpd = false;
    enableDebugXl2tpd = false;
    enableDebugXl2tpdNetwork = false;
    enableDebugXl2tpdpacket = false;
    enableDebugXl2tpdstate = false;
    enableDebugXl2tpdtunnel = 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;
    OpenvpnNeedSecurityParameter = false;
    haveUserData = false;
    prefDlgOpen=false;

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

    DebugBackgroundcolor = QColor("black");

    ToolList = new QList<ToolInfo *>();
    AccountList = new QList<VpnAccountData *>();

    InfoLogColor = QColor("black");
    ErrorLogColor = QColor("red");
    SuccessLogColor = QColor("darkGreen");
    DebugLogColor = QColor("yellow");

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

    currentProfile = 0L;
	wallet = 0L;
}

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

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

void KVpncConfig::appendLogEntry(QString msg, KVpncEnum::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.setFileName(logfileName);
            if (!logfile.open(QIODevice::WriteOnly | QIODevice::Append))
                KMessageBox::error(0, i18n("Log file cannot 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 KVpncEnum::info:
                prefix = i18n("info") + ": ";
                break;
            case KVpncEnum::remote:
                prefix = i18n("remote") + ": ";
                break;
            case KVpncEnum::error:
                prefix = i18n("error") + ": ";
                break;
            case KVpncEnum::success:
                prefix = i18n("success") + ": ";
                break;
            case KVpncEnum::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>";

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

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

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

    LogOutput->append(QString(prefix + msg + postfix));
    if (appPointer->hasPendingEvents())
        appPointer->processEvents();

}

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

}

void KVpncConfig::saveOptions(bool saveOneProfile, QString Profile)
{
    if (saveOneProfile && Profile.isEmpty())
        return;
    KConfigGroup configgroup = KGlobal::config()->group("Notification Messages");
    configgroup.writeEntry("hideOnCloseInfo" , hideOnCloseInfo);

    if (!saveOneProfile) {
        KConfigGroup configgroup = KGlobal::config()->group("General Options");

        checkStandardPathValues();

        configgroup.writeEntry("Minimize after connect", minimizeAfterConnect);
        configgroup.writeEntry("Hide on startup", hideMainWindow);
        configgroup.writeEntry("Use silent quit", useSilentQuit);
        configgroup.writeEntry("Dont quit on CloseEvent", dontQuitOnCloseEvent);
        configgroup.writeEntry("Enable pppd debug", enableDebugPppd);
        configgroup.writeEntry("Enable pptpd debug", enableDebugPptpd);
        configgroup.writeEntry("Enable l2tpd debug", enableDebugL2tpd);
        configgroup.writeEntry("Enable xl2tpd debug", enableDebugXl2tpd);
        configgroup.writeEntry("Enable openl2tp debug", enableDebugOpenl2tp);
        configgroup.writeEntry("Enable FreeSWAN verbose", enableFreeswanVerbose);
        configgroup.writeEntry( "Pluto Debug", PlutoDebug.join(" "));
        configgroup.writeEntry( "Klips Debug", KlipsDebug.join(" "));
        configgroup.writeEntry("Show debugconsole", showDebugConsole);
        configgroup.writeEntry("Pid file for vpnc ", Vpnc_pid_file);
        configgroup.writeEntry("Vpnc debuglevel", VpncDebugLevel);
        configgroup.writeEntry("Racoon debuglevel", RacoonDebugLevel);
        configgroup.writeEntry("Kvpnc debuglevel", KvpncDebugLevel);
        configgroup.writeEntry("Pppd debuglevel", PppdDebugLevel);
        configgroup.writeEntry("Pppd kernel log level", PppdKernelLogLevel);
        configgroup.writeEntry("Openvpn debuglevel", OpenvpnDebugLevel);
        configgroup.writeEntry("Pptp debuglevel", PptpLogLevel);
        configgroup.writeEntry("Ssh debuglevel", SshDebugLevel);
        configgroup.writeEntry("Pppd kernel log level", PppdKernelLogLevel);
        configgroup.writeEntry("Path to vpnc-bin", pathToVpnc);
        configgroup.writeEntry("Path to vpnclient", pathToCiscoVpnc);
        configgroup.writeEntry("Path to racoon", pathToRacoon);
        configgroup.writeEntry("Path to racoonctl", pathToRacoonctl);
        configgroup.writeEntry("Path to setkey", pathToSetkey);
        configgroup.writeEntry("Path to iptables", pathToIptables);
        configgroup.writeEntry("Path to openssl", pathToOpenssl);
        configgroup.writeEntry("Path to freeswan", pathToIpsec);
        configgroup.writeEntry("Path to pppd", pathToPppd);
        configgroup.writeEntry("Path to pptp", pathToPptp);
        configgroup.writeEntry("Path to l2tpd", pathToL2tpd);
        configgroup.writeEntry("Path to xl2tpd", pathToXl2tpd);
        configgroup.writeEntry("Path to openl2tp", pathToOpenl2tp);
        configgroup.writeEntry("Path to kill", pathToKill);
        configgroup.writeEntry("Path to kill-all", pathToKillall);
        configgroup.writeEntry("Path to ping", pathToPing);
        configgroup.writeEntry("Path to openvpn", pathToOpenvpn);
        configgroup.writeEntry("Path to iputility", pathToIp);
        configgroup.writeEntry("Path to ifconfig", pathToIfconfig);
        configgroup.writeEntry("Path to route", pathToRoute);
        configgroup.writeEntry("Path to netstat", pathToNetstat);
        configgroup.writeEntry("Path to pkcs11-tool", pathToPkcs11Tool);
        configgroup.writeEntry("Path to vtund", pathToVtund);
        configgroup.writeEntry("Path to cisco_cert_mgr", pathToCiscoCertMgr);
        configgroup.writeEntry("Path to tail", pathToTail);
        configgroup.writeEntry("Path to ssh", pathToSsh);
        configgroup.writeEntry("Path to ksshaskpass", pathToKsshAskpass);
        configgroup.writeEntry("Path to ssh-askpass-gnome", pathToGnomeSshAskpass);
        configgroup.writeEntry("Show Statusbar", showStatusBar);
        configgroup.writeEntry("Try connect timeout", tryConnectTimeout);
        configgroup.writeEntry("Last Profile", lastProfile);
        configgroup.writeEntry("Write log file", writeLogFile);
        configgroup.writeEntry("Hold generated scripts", holdGeneratedScripts);
        configgroup.writeEntry("Programs in path", programsInPath);
        configgroup.writeEntry("Info logwindow color", InfoLogColor);
        configgroup.writeEntry("Remote logwindow color", RemoteLogColor);
        configgroup.writeEntry("Error logwindow color", ErrorLogColor);
        configgroup.writeEntry("Success  logwindow color", SuccessLogColor);
        configgroup.writeEntry("Debug logwindow color", DebugLogColor);
        configgroup.writeEntry("Debug background color", DebugBackgroundcolor);
        configgroup.writeEntry("Use colorized log output", useColorizedLogOutput);
        configgroup.writeEntry("Show interface IP in tooltip", showInterfaceIPinTooltip);
        configgroup.writeEntry("Auto connect profile", AutoConnectProfile);
        configgroup.writeEntry("Do auto connect at startup", doAutoConnectAtStartup);
        configgroup.writeEntry("Log viewer font size", LogViewerFontSize);
        configgroup.writeEntry("Mainwindow width", parent->width());
        configgroup.writeEntry("Mainwindow height", parent->height());
        configgroup.writeEntry("Mainwindow position x", parent->x());
        configgroup.writeEntry("Mainwindow position y", parent->y());
        configgroup.writeEntry("Openvpn management port", OpenvpnManagementPort);
        //configgroup.writeEntry( "ToolBar Settings" ,parent->toolBar( "mainToolBar" ));
        configgroup.writeEntry("Use KWallet", useKwallet);
        configgroup.writeEntry("FeedbackMailSent", feedbackMailSent);
        configgroup.writeEntry("Do kill l2tpd if still running", doKillL2tpdIfStillRunning);
        configgroup.writeEntry("Do kill racoon if still running", doKillRacoonIfStillRunning);
        configgroup.writeEntry("Do kill xl2tpd if still running", doKillXl2tpdIfStillRunning);
        configgroup.writeEntry("Show connection time in Tooltip", showConnectionTimeInTooltip);
        configgroup.writeEntry("Enable debug Openvpn", enableDebugOpenvpn);
        configgroup.writeEntry("Do kill l2tpd if still running", doKillL2tpdIfStillRunning);
        configgroup.writeEntry("Do kill racoon if still running", doKillRacoonIfStillRunning);
        configgroup.writeEntry("Do kill xl2tpd if still running", doKillXl2tpdIfStillRunning);
        configgroup.writeEntry("Show connection time in Tooltip", showConnectionTimeInTooltip);
        configgroup.writeEntry("Enable debug Openvpn", enableDebugOpenvpn);
        configgroup.writeEntry("EnableDebugXl2tpdNetwork", enableDebugXl2tpdNetwork);
        configgroup.writeEntry("EnableDebugXl2tpdpacket", enableDebugXl2tpdpacket);
        configgroup.writeEntry("EnableDebugXl2tpdstate", enableDebugXl2tpdstate);
        configgroup.writeEntry("EnableDebugXl2tpdtunnel", enableDebugXl2tpdtunnel);

        //appPointer->processEvents();
    }

    configgroup = KGlobal::config()->group("General Options");
    if (useKwallet && KWallet::Wallet::isEnabled())
        configgroup.writeEntry("First use of Kwallet", false);
    /* = user data = */
    VpnAccountData *it = NULL;
    if (!AccountList->isEmpty()) {
        /* passwords with kwallet */
        if (useKwallet && KWallet::Wallet::isEnabled()) {
            if (!skipKwalletStoring) {
                if (KvpncDebugLevel > 2)
                    appendLogEntry(i18n("Wallet enabled and available, writing to wallet."), KVpncEnum::debug);
                // Open local wallet
                wallet = KWallet::Wallet::openWallet(KWallet::Wallet::LocalWallet(), parent->winId());
                //appPointer->processEvents();
                if (wallet != 0) {
                }
            }
        } else {
            if (KvpncDebugLevel > 2)
                appendLogEntry(i18n("Wallet disabled or not available, writing to config file."), KVpncEnum::debug);
        }

        QList<VpnAccountData *> *TmpAccountList;

        if (!saveOneProfile)
            TmpAccountList = AccountList;
        else {
            if (KvpncDebugLevel > 2)
                appendLogEntry(i18n("Save only specified profile: %1", Profile), KVpncEnum::debug);
            TmpAccountList = new QList<VpnAccountData *>();
            VpnAccountData *ProfileData;

            for (int accountIdx = 0; accountIdx < AccountList->size(); ++accountIdx) {
                ProfileData = AccountList->at(accountIdx);
                if (ProfileData->getName() == Profile) {
                    TmpAccountList->append(ProfileData);
                    break;
                }
            }
        }

        for (int accountIdx = 0; accountIdx < TmpAccountList->size(); ++accountIdx) {
            it = TmpAccountList->at(accountIdx);

            if (!it->getName().isEmpty()) {
                QString name = it->getName();
                QString ProfileName = "Profile_";
                ProfileName += name;
                KConfigGroup configgroup = KGlobal::config()->group(ProfileName);

                configgroup.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."), KVpncEnum::debug);
                        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);
                                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();

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

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


                                if (UserPasswordOK) {
                                    if (KvpncDebugLevel > 2) {
                                        appendLogEntry(i18n("Writing %1 was successful.",
                                                            i18n("user password")),
                                                       KVpncEnum::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?" , QString(i18n("user password"))),
                                        //                  i18n( "Unable to store secure %1" , QString(i18n("user password"))),
                                        //                  KGuiItem( i18n( "Store &Unsafe" ), QLatin1String( "unlock" ),QString::fromLatin1( "KWalletFallbackToKConfig" ) ) ) == KMessageBox::Continue )
                                        //          {
                                        //           configgroup.writeEntry( "User password", it->getUserPassword() );
                                        //          }

                                        appendLogEntry(i18n("Writing %1 has failed.",
                                                            i18n("user password")),
                                                       KVpncEnum::error);
                                    }
                                }

                                if (PskOK) {
                                    if (KvpncDebugLevel > 2) {
                                        appendLogEntry(i18n("Writing %1 was successful.", i18n("preshared key")), KVpncEnum::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?", QString(i18n("pre shared key"))),
                                        //                  i18n( "Unable to store secure %1" , QString(i18n("pre shared key"))),
                                        //                  KGuiItem( i18n( "Store &Unsafe" ), QLatin1String( "unlock" ),QString::fromLatin1( "KWalletFallbackToKConfig" ) ) ) == KMessageBox::Continue )
                                        //          {
                                        //           configgroup.writeEntry( "Pre shared key", it->getPreSharedKey() );
                                        //          }
                                        appendLogEntry(i18n("Writing %1 has failed.", i18n("preshared key")), KVpncEnum::error);
                                    }
                                }

                                if (PskKeyPassOK) {
                                    if (KvpncDebugLevel > 2) {
                                        appendLogEntry(i18n("Writing %1 was successful.",
                                                            i18n("preshared key password")),
                                                       KVpncEnum::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?" , QString(i18n("preshared key password"))),
                                        //                  i18n( "Unable to store secure %1" , QString(i18n("reshared key password"))),
                                        //                  KGuiItem( i18n( "Store &Unsafe" ), QLatin1String( "unlock" ),QString::fromLatin1( "KWalletFallbackToKConfig" ) ) ) == KMessageBox::Continue )
                                        //          {
                                        //           configgroup.writeEntry( "Pre shared key", it->getPreSharedKey() );
                                        //          }
                                        appendLogEntry(i18n("Writing %1 has failed.", i18n("preshared key password")), KVpncEnum::error);
                                    }
                                }
                                wallet->sync();
                                if (appPointer->hasPendingEvents())
                                    appPointer->processEvents();
                            } else {
                                KMessageBox::error(0, i18n("Unable to create wallet folder for kvpnc."));
                                appendLogEntry(i18n("Unable to create wallet folder for kvpnc."), KVpncEnum::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."), KVpncEnum::debug);
                    }
                } else { //Wallet not available
                    //if (!useKwallet)
                    {
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Wallet disabled or not available, writing to config file."), KVpncEnum::debug);
                        // write passwords to config file :|
                        if (it->getSaveUserPassword()) {
                            configgroup.writeEntry("User password", it->getUserPassword());
                        }
                        if (it->getSavePsk()) {
                            configgroup.writeEntry("Pre shared key", it->getPreSharedKey());
                        }
                        configgroup.writeEntry("PrivateKey password", it->getPrivateKeyPass());
                    }
                }

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

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

                configgroup.writeEntry("Save user password", it->getSaveUserPassword());
                configgroup.writeEntry("Save PSK", it->getSavePsk());
                configgroup.writeEntry("Save private key password", it->getSavePrivateKeyPassword());
                configgroup.writeEntry("Private key", it->getPrivateKey());
                configgroup.writeEntry("Use advanced settings", it->getUseAdvancedSettings());
                configgroup.writeEntry("Application version", it->getApplicationVersion());
                configgroup.writeEntry("Local port", it->getLocalPort());
                configgroup.writeEntry("Remote port", it->getRemotePort());
                configgroup.writeEntry("NT domain name", it->getNtDomainName());
                configgroup.writeEntry("Perfect forward secrety", it->getPerfectForwardSecrety());
                configgroup.writeEntry("IKE group", it->getIkeGroup());

                configgroup.writeEntry("Use application version", it->getUseApplicationVersion());
                configgroup.writeEntry("Use global IPSec secret", it->getUseGlobalIpsecSecret());
                configgroup.writeEntry("Use IKE group", it->getUseIkeGroup());
                configgroup.writeEntry("Use local port", it->getUseLocalPort());
                configgroup.writeEntry("Use remote port", it->getUseRemotePort());
                configgroup.writeEntry("Use NT domain name", it->getUseNtDomainName());
                configgroup.writeEntry("Use single DES", it->getUseSingleDes());
                configgroup.writeEntry("Use perfect Forward Secrety", it->getUsePerfectForwardSecrety());
                configgroup.writeEntry("Remote net address", it->getRemoteNetAddr());
                configgroup.writeEntry("Remote net mask", it->getRemoteNetMask());

                configgroup.writeEntry("x509 certificate", it->getX509Certificate());
                configgroup.writeEntry("Ca certificate", it->getCaCertificate());
                configgroup.writeEntry("Network device", it->getNetworkDevice());
                configgroup.writeEntry("Cert path", it->getCertPath());
                //// fix bad type
                //if ((it->getConnectionType() == VpnAccountData::pptp || it->getConnectionType() == VpnAccountData::openvpn || it->getConnectionType() == VpnAccountData::racoon || it->getConnectionType() == VpnAccountData::l2tpd_racoon || it->getConnectionType() == VpnAccountData::freeswan || it->getConnectionType() == VpnAccountData::l2tpd_freeswan || it->getConnectionType() == VpnAccountData::vtun) && ( it->getAuthType() != "cert" || it->getAuthType() != "psk"))
                //{
                //	it->setAuthType( VpnAccountData::cert);
                //}

                if (it->getAuthType() == VpnAccountData::cert)
                    configgroup.writeEntry("Auth type", "cert");
                else if (it->getAuthType() == VpnAccountData::psk)
                    configgroup.writeEntry("Auth type", "psk");
                else if (it->getAuthType() == VpnAccountData::hybrid)
                    configgroup.writeEntry("Auth type", "hybrid");
                else
                    configgroup.writeEntry("Auth type", "unknownauth");

                configgroup.writeEntry("do ping ip", it->getDoPingIP());
                configgroup.writeEntry("Ping host IP", it->getPingHostIP());
                configgroup.writeEntry("Use special remote ID", it->getUseSpecialRemoteID());
                configgroup.writeEntry("Use special local ID", it->getUseSpecialLocalID());
                configgroup.writeEntry("Special server certificate", it->getSpecialServerCertificate());
                configgroup.writeEntry("Use special server certificate", it->getUseSpecialServerCertificate());
                configgroup.writeEntry("Special remote ID", it->getSpecialRemoteID());
                configgroup.writeEntry("Special local ID", it->getSpecialLocalID());
                configgroup.writeEntry("Local ID type", it->getLocalIDType());
                configgroup.writeEntry("Remote ID type", it->getRemoteIDType());
                configgroup.writeEntry("Use UDP-protocol", it->getUseUdp());
                configgroup.writeEntry("Use UDP-port", it->getUseUdpPort());
                configgroup.writeEntry("local UDP port", it->getUdpPort());
                configgroup.writeEntry("use DNS_UPDATE", it->getUseDnsUpdate());
                configgroup.writeEntry("use DNS-server", it->getUseDnsServer());
                configgroup.writeEntry("DNS server", it->getDnsServer());
                configgroup.writeEntry("refuse 40 bit encryption", it->getRefuse40BitEncryption());
                configgroup.writeEntry("refuse 128 bit encryption", it->getRefuse128BitEncryption());
                configgroup.writeEntry("require stateless encryption", it->getAllowStatefulMode());
                configgroup.writeEntry("require mppe", it->getRequireMppe());
                configgroup.writeEntry("Disable MPPE compression", it->getDisableMPPEComp());
                configgroup.writeEntry("Local virtual IP", it->getLocalVirtualIP());
                configgroup.writeEntry("Remote virtual IP", it->getRemoteVirtualIP());
                configgroup.writeEntry("Pre shared key file", it->getPreSharedKeyFile());
                configgroup.writeEntry("Execute command before connect", it->getExecuteCmdBeforeConnect());
                configgroup.writeEntry("Execute command after connect", it->getExecuteCmdAfterConnect());
                configgroup.writeEntry("Execute command before disconnect", it->getExecuteCmdBeforeDisconnect());
                configgroup.writeEntry("Execute command after disconnect", it->getExecuteCmdAfterDisconnect());
                configgroup.writeEntry("Command before connect", it->getCommandBeforeConnect());
                configgroup.writeEntry("Command after connect", it->getCommandAfterConnect());
                configgroup.writeEntry("Command before disconnect", it->getCommandBeforeDisconnect());
                configgroup.writeEntry("Command after disconnect", it->getCommandAfterDisconnect());
                configgroup.writeEntry("Use no BSD compression", it->getUseNoBsdComp());
                configgroup.writeEntry("Do not use no IP by default", it->getUseNoIpDefault());
                configgroup.writeEntry("Use no deflate", it->getUseNoDeflate());
                configgroup.writeEntry("Replace default route", it->getReplaceDefaultRoute());
                configgroup.writeEntry("Use own MTU", it->getUseMtu());
                configgroup.writeEntry("Use own MRU", it->getUseMru());
                configgroup.writeEntry("MTU for pppd", it->getMtu());
                configgroup.writeEntry("MRU for pppd", it->getMru());
                configgroup.writeEntry("Use virtual IP", it->getUseVirtualIP());
                configgroup.writeEntry("Virtual IP", it->getVirtualIP());
                configgroup.writeEntry("PSK is in file", it->getPskIsInFile());
                configgroup.writeEntry("Use additional network routes", it->getUseAdditionalNetworkRoutes());
                configgroup.writeEntry("Hash algorithm", it->getHashAlgo());
                configgroup.writeEntry("Encryption algorithm", it->getEncryptionAlgorithm());
                configgroup.writeEntry("Authentication algorithm", it->getAuthenticationAlgorithm());
                configgroup.writeEntry("Tunnel device type", it->getTunnelDeviceType());
                configgroup.writeEntry("Use userdefined port", it->getUseUserdefinedPort());
                configgroup.writeEntry("Userdefined port", it->getUserdefinedPort());
                configgroup.writeEntry("NS cert type", it->getNsCertType());
                configgroup.writeEntry("Use NS cert type", it->getUseNsCertType());
                configgroup.writeEntry("Use connection status check", it->getUseConnectionStatusCheck());
                configgroup.writeEntry("Connection check success count", it->getConnectionStatusCheckSuccessCount());
                configgroup.writeEntry("Connection check status interval", it->getConnectionStatusInterval());
                configgroup.writeEntry("Do reconnect after connection lost", it->getDoReconnectAfterConnectionLost());
                configgroup.writeEntry("Disable LZO compression", it->getDisableLzoCompression());
                configgroup.writeEntry("AuthWithUsernameAndPassword", it->getAuthWithUsernameAndPassword());
                configgroup.writeEntry("AllowEmptyGroupPassword", it->getAllowEmptyGroupPassword());
                configgroup.writeEntry("Use userdefinied cipher", it->getUseUserdefiniedCipher());
                configgroup.writeEntry("Userdefinied cipher", it->getUserdefiniedCipher());
                configgroup.writeEntry("Use redirect gateway", it->getUseRedirectGateway());
                configgroup.writeEntry("Use TLS auth", it->getUseTlsAuth());
                configgroup.writeEntry("TLS auth file", it->getTlsAuthFile());
                configgroup.writeEntry("Use HTTP proxy", it->getUseHttpProxy());
                configgroup.writeEntry("HTTP proxy host", it->getHttpProxy());
                configgroup.writeEntry("HTTP proxy port", it->getHttpProxyPort());
                configgroup.writeEntry("HTTP proxy timeout", it->getHttpProxyTimeout());
                configgroup.writeEntry("Dont save username", it->getDontSaveUsername());
                configgroup.writeEntry("Use mode config", it->getUseModeConfig());
                configgroup.writeEntry("Exchange mode", it->getExchangeMode());
                configgroup.writeEntry("Use delay at reconnect", it->getUseReconnectDelay());
                configgroup.writeEntry("Reconnect delay", it->getReconnectDelay());
                configgroup.writeEntry("Use TLS host", it->getUseTlsRemoteHost());
                configgroup.writeEntry("TLS remote host", it->getTlsRemoteHost());
                configgroup.writeEntry("Disable opportunistic encryption", it->getDisableOpportunisticEncryption());
                configgroup.writeEntry("Right next hop", it->getRightNextHop());
                configgroup.writeEntry("Left next hop", it->getLeftNextHop());
                configgroup.writeEntry("Use userdefinied packet size for fragmentation", it->getUseFragment());
                configgroup.writeEntry("Use userdef packet size", it->getUseMssfix());
                configgroup.writeEntry("Fragment", it->getFragment());
                configgroup.writeEntry("PeerTimeout", it->getPeerTimeout());
                configgroup.writeEntry("Disable CCP", it->getDisableCcp());
                configgroup.writeEntry("Use smartcard", it->getUseSmartcard());
                configgroup.writeEntry("Use Xauth interactive", it->getUseXauthInteractive());
                configgroup.writeEntry("Use HTTP Proxy Authentication", it->getUseHttpProxyAuth());
                configgroup.writeEntry("HTTP Proxy Authtype", it->getHttpProxyAuthType());
                configgroup.writeEntry("HTTP Proxy Auth user", it->getHttpProxyUser());
                configgroup.writeEntry("HTTP Proxy Auth pass", it->getHttpProxyPass());
                configgroup.writeEntry("Use only CA cert and user auth", it->getUseOnlyCaCertAndUserAuth());
                configgroup.writeEntry("Use mail address as identifier", it->getUseMailAddressAsIdentifier());
                configgroup.writeEntry("Use right next hop", it->getUseRightNextHop());
                configgroup.writeEntry("Use left next hop", it->getUseLeftNextHop());
                configgroup.writeEntry("Pkcs11 providers", it->getPkcs11Providers());
                configgroup.writeEntry("Pkcs11 slot type", it->getPkcs11SlotType());
                configgroup.writeEntry("Pkcs11 slot", it->getPkcs11Slot());
                configgroup.writeEntry("Pkcs11 id type", it->getPkcs11IdType());
                configgroup.writeEntry("Pkcs11 id", it->getPkcs11Id());
                configgroup.writeEntry("Pkcs11 sign mode", it->getPkcs11SignMode());
                configgroup.writeEntry("Use Pkcs11 providers", it->getUsePkcs11Providers());
                configgroup.writeEntry("Allow empty private key password", it->getAllowEmptyPrivateKeyPassword());
                configgroup.writeEntry("Allow ip address change of peer", it->getAllowIpAddressChangeOfPeer());
                configgroup.writeEntry("Auth method", it->getAuthMethod());
                configgroup.writeEntry("Command after connect delay time", it->getCommandAfterConnectDelayTime());
                configgroup.writeEntry("Use search domain in resolv conf", it->getUseSearchDomainInResolvConf());
                configgroup.writeEntry("Search domain in resolv conf", it->getSearchDomainInResolvConf());
                configgroup.writeEntry("Authentication direction", it->getAuthenticationDirection());
                configgroup.writeEntry("CiscoNatMode", it->getCiscoNatMode());
                configgroup.writeEntry("IPSec ESP", it->getIpsecEsp());
                configgroup.writeEntry("IPSec IKE", it->getIpsecIke());
                configgroup.writeEntry("Vtun profile", it->getVtunProfile());
                configgroup.writeEntry("Disable data encryption", it->getDisableDataEncryption());
                configgroup.writeEntry("Use authentication algorithm", it->getUseAuthenticationAlgorithm());
                configgroup.writeEntry("Fix path mtu discovery problem" , it ->getFixPathMtuDiscoveryProblem());
                configgroup.writeEntry("Use remote network", it->getUseRemoteNetwork());
                configgroup.writeEntry("Ipsec vpn mode", it->getIpsecVpnMode());
                configgroup.writeEntry("DisableHeaderCompression", it->getDisableHeaderCompression());
                configgroup.writeEntry("DisableMagicNumberNegotiation", it->getDisableMagicNumberNegotiation());
                configgroup.writeEntry("DisableIpx", it->getDisableIpx());
                configgroup.writeEntry("Disable protocol field compression", it->getDisableProtocolFieldCompression());
                configgroup.writeEntry("Disable address control compression", it->getDisableAddressControlCompression());
                configgroup.writeEntry("Use custom ike", it->getUseCustomIke());
                configgroup.writeEntry("Use custom esp", it->getUseCustomEsp());
                configgroup.writeEntry("Verify ca cert", it->getVerifyCaCert());
                configgroup.writeEntry("Use DPD idle timeout", it->getUseDpdIdleTimeout());
                configgroup.writeEntry("DPD idle timeout", it->getDpdIdleTimeout());
                configgroup.writeEntry("Hide group password in accountdata dialog", it->getHideGroupPasswordInAccountDataDialog());
                configgroup.writeEntry("MaxConnectTries", it->getMaxConnectTries());
                configgroup.writeEntry("L2tpDaemon", (int) it->getL2tpDaemon());
                configgroup.writeEntry("UseLeftSourceIp", it->getUseLeftSourceIp());
                configgroup.writeEntry("UseRightSourceIp", it->getUseRightSourceIp());
                configgroup.writeEntry("LeftSourceIp", it->getLeftSourceIp());
                configgroup.writeEntry("RightSourceIp", it->getRightSourceIp());
                configgroup.writeEntry("Use virtual subnets", it->getUseVirtualSubnetworks());
                configgroup.writeEntry("Virtual subnets", it->getVirtualSubnetworks());
                configgroup.writeEntry("DisablePushFromServer", it->getDisablePushFromServer());
                configgroup.writeEntry("DisableBind", it->getDisableBind());
                configgroup.writeEntry("UseRenegSec", it->getUseRenegSec());
                configgroup.writeEntry("RenegSec", it->getRenegSec());
                configgroup.writeEntry("UseTunnelPing", it->getUseTunnelPing());
                configgroup.writeEntry("TunnelPing", it->getTunnelPing());
                configgroup.writeEntry("UseTunnelPingRestart", it->getUseTunnelPingRestart());
                configgroup.writeEntry("TunnelPingRestart", it->getTunnelPingRestart());
                configgroup.writeEntry("RequireEap", it->getRequireEap());
                configgroup.writeEntry("UseSshConfigRemoteScript", it->getUseSshConfigRemoteScript());
                configgroup.writeEntry("SshConfigRemoteScript", it->getSshConfigRemoteScript());
                configgroup.writeEntry("AskUserPasswordOnEachConnect", it->getAskUserPasswordOnEachConnect());
                configgroup.writeEntry("UseCiscoCertStore", it->getUseCiscoCertStore());
                configgroup.writeEntry("UseNat", it->getUseNat());

                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);
                configgroup.writeEntry("Additional network routes", AdditionalNetworkRoutesString);

                //wallet->sync();
                /* give info */
                //slotStatusMsg ( i18n( "Profile \"%1\" saved." , QString(it->getName().remove("Profile_") )), ID_FLASH_MSG );

                appendLogEntry(i18n("Profile \"%1\" saved." ,  it->getName().remove("Profile_")) , KVpncEnum::info);
                //appPointer->processEvents();
            }
            //         wallet->sync();

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


//  if ( !skipKwalletStoring && wallet != 0)
//   if (useKwallet && KWallet::Wallet::isEnabled())
//    if (wallet->isOpen())
//     wallet->sync();
    configgroup.sync();
    doBackupConfig();

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

void KVpncConfig::loadOptions()
{
    KConfigGroup configgroup = KGlobal::config()->group("Notification Messages");
    hideOnCloseInfo =  configgroup.readEntry("hideOnCloseInfo" , "0").toInt();

    configgroup = KGlobal::config()->group("General Options");
    minimizeAfterConnect = QVariant(configgroup.readEntry("Minimize after connect", true)).toBool();
    hideMainWindow = QVariant(configgroup.readEntry("Hide on startup", false)).toBool();
    useSilentQuit = QVariant(configgroup.readEntry("Use silent quit", false)).toBool();
    dontQuitOnCloseEvent = QVariant(configgroup.readEntry("Dont quit on CloseEvent", true)).toBool();
    showDebugConsole = QVariant(configgroup.readEntry("Show debugconsole", true)).toBool();
    enableDebugPppd = QVariant(configgroup.readEntry("Enable pppd debug", false)).toBool();
    enableDebugPptpd = QVariant(configgroup.readEntry("Enable pptpd debug", false)).toBool();
    enableFreeswanVerbose = QVariant(configgroup.readEntry("Enable FreeSWAN verbose", false)).toBool();
    PlutoDebug = QStringList::split(" ", configgroup.readEntry( "Pluto Debug", ""));
    KlipsDebug = QStringList::split(" ", configgroup.readEntry( "Klips Debug", ""));
    Vpnc_pid_file = configgroup.readEntry("Pid file for vpnc ", "/var/run/vpnc/pid");
    RacoonDebugLevel = configgroup.readEntry("Racoon debuglevel", "notify");
    // we need to correct old int value
    if (RacoonDebugLevel == "0")
        RacoonDebugLevel="info";
    if (RacoonDebugLevel != "info" && RacoonDebugLevel != "debug" && RacoonDebugLevel != "debug2" )
        RacoonDebugLevel = "info";

    VpncDebugLevel =  QVariant(configgroup.readEntry("Vpnc debuglevel", false)).toBool();
    KvpncDebugLevel = QVariant(configgroup.readEntry("Kvpnc debuglevel", "1")).toInt();
    PppdDebugLevel = QVariant(configgroup.readEntry("Pppd debuglevel", false)).toBool();
    PppdKernelLogLevel = QVariant(configgroup.readEntry("Pppd kernel log level", "0")).toInt();
    OpenvpnDebugLevel = QVariant(configgroup.readEntry("Openvpn debuglevel", false)).toBool();
    PptpLogLevel =  QVariant(configgroup.readEntry("Pptp debuglevel", true)).toBool();
    SshDebugLevel = QVariant(configgroup.readEntry("ssh debuglevel", 1)).toInt();
    enableDebugL2tpd = QVariant(configgroup.readEntry("enable l2tpd debug", false)).toBool();
    enableDebugXl2tpd = QVariant(configgroup.readEntry("Enable xl2tpd debug", false)).toBool();
    enableDebugOpenl2tp = QVariant(configgroup.readEntry("Enable openl2tp debug", false)).toBool();

    enableDebugXl2tpdNetwork = QVariant(configgroup.readEntry("EnableDebugXl2tpdNetwork", false)).toBool();
    enableDebugXl2tpdpacket = QVariant(configgroup.readEntry("EnableDebugXl2tpdpacket", false)).toBool();
    enableDebugXl2tpdstate = QVariant(configgroup.readEntry("EnableDebugXl2tpdstate", false)).toBool();
    enableDebugXl2tpdtunnel = QVariant(configgroup.readEntry("EnableDebugXl2tpdtunnel", false)).toBool();


    pathToVpnc = configgroup.readEntry("Path to vpnc-bin", "/usr/sbin/vpnc");
    pathToCiscoVpnc = configgroup.readEntry("Path to vpnclient", "/usr/local/bin/vpnclient");
    pathToSetkey = configgroup.readEntry("Path to setkey", "/usr/sbin/setkey");
    pathToRacoon = configgroup.readEntry("Path to racoon", "/usr/sbin/racoon");
    pathToRacoonctl = configgroup.readEntry("Path to racoonctl", "/usr/sbin/racoonctl");
    pathToIptables = configgroup.readEntry("Path to iptables", "/sbin/iptables");
    pathToOpenssl = configgroup.readEntry("Path to openssl", "/usr/bin/openssl");
    pathToIpsec = configgroup.readEntry("Path to freeswan", "/usr/sbin/ipsec");
    pathToIp = configgroup.readEntry("Path to iputility", "/sbin/ip");
    pathToIfconfig = configgroup.readEntry("Path to ifconfig", "/sbin/ifconfig");
    pathToRoute = configgroup.readEntry("Path to route", "/sbin/route");
    pathToNetstat = configgroup.readEntry("Path to netstat", "/bin/netstat");
    pathToPppd = configgroup.readEntry("Path to pppd", "/usr/sbin/pppd");
    pathToPptp = configgroup.readEntry("Path to pptp", "/usr/sbin/pptp");
    pathToL2tpd = configgroup.readEntry("Path to l2tpd", "/usr/sbin/l2tpd");
    pathToXl2tpd = configgroup.readEntry("Path to xl2tpd", "/usr/sbin/xl2tpd");
    pathToOpenl2tp = configgroup.readEntry("Path to openl2tp", "/usr/sbin/openl2tpd");
    pathToKill = configgroup.readEntry("Path to kill", "/bin/kill");
    pathToKillall = configgroup.readEntry("Path to kill-all", "/usr/bin/killall");
    pathToPing = configgroup.readEntry("Path to ping", "/bin/ping");
    pathToOpenvpn = configgroup.readEntry("Path to openvpn", "/usr/sbin/openvpn");
    pathToPkcs11Tool = configgroup.readEntry("Path to pkcs11-tool", "/usr/bin/pkcs11-tool");
    pathToVtund = configgroup.readEntry("Path to vtund", "/usr/sbin/vtund");
    pathToCiscoCertMgr = configgroup.readEntry("Path to cisco_cert_mgr", "/usr/local/bin/cisco_cert_mgr");
    pathToTail = configgroup.readEntry("Path to tail", "/usr/bin/tail");
    pathToSsh = configgroup.readEntry("Path to ssh", "/usr/bin/ssh");
    pathToKsshAskpass = configgroup.readEntry("Path to ksshaskpass", "/usr/bin/ksshaskpass");
    pathToGnomeSshAskpass = configgroup.readEntry("Path to ssh-askpass-gnome", "/usr/lib/openssh/gnome-ssh-askpass");

    checkStandardPathValues();

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


    if (programsInPath)
        useDefaultPaths = true;

    InfoLogColor =  QVariant(configgroup.readEntry("Info logwindow color", QColor("black"))).value<QColor>();
    RemoteLogColor =  QVariant(configgroup.readEntry("Remote logwindow color", QColor("blue"))).value<QColor>();
    ErrorLogColor =  QVariant(configgroup.readEntry("Error logwindow color", QColor("red"))).value<QColor>();
    SuccessLogColor =  QVariant(configgroup.readEntry("Success  logwindow color", QColor("darkGreen"))).value<QColor>();
    DebugLogColor =  QVariant(configgroup.readEntry("Debug logwindow color", QColor("gray"))).value<QColor>();
    DebugBackgroundcolor =  QVariant(configgroup.readEntry("Debug background color", QColor("white"))).value<QColor>();
    useColorizedLogOutput =  QVariant(configgroup.readEntry("Use colorized log output", true)).toBool();
    showInterfaceIPinTooltip = QVariant(configgroup.readEntry("Show interface IP in tooltip", true)).toBool();
    AutoConnectProfile = configgroup.readEntry("Auto connect profile", "");
    doAutoConnectAtStartup = QVariant(configgroup.readEntry("Do auto connect at startup", true)).toBool();
    LogViewerFontSize = configgroup.readEntry("Log viewer font size", "2").toInt();

    WindowSize = QSize(configgroup.readEntry("Mainwindow width", "50").toInt(), configgroup.readEntry("Mainwindow height", "50").toInt());
    WindowPos = QPoint(configgroup.readEntry("Mainwindow position x", "10").toInt(), configgroup.readEntry("Mainwindow position y", "50").toInt());

    OpenvpnManagementPort = configgroup.readEntry("Openvpn management port", "2222").toInt();

    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" , QString(dirs->saveLocation( "data" )+"/kvpnc" )));
                QDir AppFolder2(dirs->saveLocation("data"));
                if (!AppFolder2.mkdir("kvpnc")) {
                    KMessageBox::error(0, i18n("The appdir for kvpnc could not be created. Be sure that you have write permission of \"%1\"." , dirs->saveLocation("data")));
                    appendLogEntry(i18n("The appdir for kvpnc could not be created. Be sure that you have write permission of \"%1\"." , dirs->saveLocation("data")), KVpncEnum::error);
                }
            }

            logfileName = dirs->saveLocation("data");
            logfileName += "/kvpnc/kvpnc.log";
            //KMessageBox::information( this, logfileName, "info" );
            logfile.setFileName(logfileName);
            if (!logfile.open(QIODevice::Append)) {
                KMessageBox::error(0, i18n("Log file cannot be opened."));
                appendLogEntry(i18n("Unable to find \"%1\"." , QString("pppd")), KVpncEnum::error);
            } else {
                QTextStream s(&logfile);
                s << i18n("Log session started at: ") << QDateTime::currentDateTime().toString(Qt::TextDate) << endl;
            }
        }
    }
    useKwallet = QVariant(configgroup.readEntry("Use KWallet", true)).toBool();
    firstUseOfKwallet = QVariant(configgroup.readEntry("First use of Kwallet", true)).toBool();
    feedbackMailSent = QVariant(configgroup.readEntry("FeedbackMailSent", false)).toBool();
    doKillL2tpdIfStillRunning = QVariant(configgroup.readEntry("Do kill l2tpd if still running", false)).toBool();
    doKillRacoonIfStillRunning = QVariant(configgroup.readEntry("Do kill racoon if still running", false)).toBool();
    doKillXl2tpdIfStillRunning = QVariant(configgroup.readEntry("Do kill xl2tpd if still running", false)).toBool();
    showConnectionTimeInTooltip = QVariant(configgroup.readEntry("Show connection time in Tooltip", true)).toBool();
    enableDebugOpenvpn = QVariant(configgroup.readEntry("Enable debug Openvpn", false)).toBool();

    if (KvpncDebugLevel > 6) {
        if (useKwallet)
            appendLogEntry(i18n("use kwallet: %1" , i18n("yes")) , KVpncEnum::debug);
        else
            appendLogEntry(i18n("use kwallet: %1" , i18n("no")) , KVpncEnum::debug);
        if (firstUseOfKwallet)
            appendLogEntry(i18n("first use kwallet: %1" , i18n("yes")) , KVpncEnum::debug);
        else
            appendLogEntry(i18n("first use kwallet: %1" , i18n("no")) , KVpncEnum::debug);
    }

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


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

    this->mw->CheckUserPass->setChecked( (bool) configgroup.readEntry( "Save user password", false ) );
    this->mw->CheckGroupPass->setChecked( (bool) configgroup.readEntry( "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 = KGlobal::config()->groupList();

    if (KvpncDebugLevel > 5)
        appendLogEntry(i18n("Config groups found: %1" , configGroups.join(",")) , KVpncEnum::debug);

    bool oldConfigurationFound = false;

    bool sessionFound = false;
    bool kwalletOpened = false;

    /* passwords with kwallet */
    if (useKwallet && KWallet::Wallet::isEnabled()) {
        if (KvpncDebugLevel > 2)
            appendLogEntry(i18n("Wallet enabled and available, reading passwords from wallet."), KVpncEnum::debug);

        if (!kwalletOpened) {
            if (KvpncDebugLevel > 2)
                appendLogEntry(i18n("Wallet is closed, try to open it..."), KVpncEnum::debug);
            // Open local wallet
            wallet = KWallet::Wallet::openWallet(KWallet::Wallet::LocalWallet(), parent->winId());
            if (wallet != 0L && wallet->isOpen()) {
                kwalletOpened = true;
                if (KvpncDebugLevel > 2)
                    appendLogEntry(i18n("Wallet opened."), KVpncEnum::debug);
            }
            else
            {
                appendLogEntry(i18n("Wallet could not be opened."), KVpncEnum::debug);
                // ok, we wait some time...
                sleep(3);
                if (wallet != 0L && wallet->isOpen()) {
                    kwalletOpened = true;
                    if (KvpncDebugLevel > 2)
                        appendLogEntry(i18n("Wallet opened (second try)."), KVpncEnum::debug);
                }
                else
                {
                    appendLogEntry(i18n("Wallet could not be opened (second try)."), KVpncEnum::debug);
                }
            }
        }
    }


    for (QStringList::Iterator it = configGroups.begin(); it != configGroups.end(); ++it) {
        QString name = *it;
        name.trimmed();
        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, KVpncEnum::debug);
            }
            configgroup = KGlobal::config()->group(name);
            QString UserPassword = "";
            QString PrivateKeyPass = "";
            QString PreSharedKey = "";


            if (useKwallet && KWallet::Wallet::isEnabled()) {
                if (kwalletOpened) {
                    QString walletname = "kvpnc";

                    if (!wallet->hasFolder(walletname)) {
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Folder for kvpnc has been created."), KVpncEnum::debug);
                        wallet->createFolder(walletname);
                        wallet->sync();
                    }

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

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

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

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

                        if (wallet->readPassword(QString(profilename + "__priv_key_pwd"), PrivateKeyPass) != 0)
                            appendLogEntry(i18n("Reading %1 has failed." , i18n("preshared key password")), KVpncEnum::error);
                        else
                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Reading %1 was successful." , i18n("preshared key password")), KVpncEnum::debug);
                    } else {
                        KMessageBox::error(0, i18n("Unable to set wallet folder for kvpnc."));
                        appendLogEntry(i18n("Unable to set wallet folder for kvpnc."), KVpncEnum::error);
                    }
                    if (appPointer->hasPendingEvents())
                        appPointer->processEvents();
                } else {
                    KMessageBox::error(0, i18n("Unable to open wallet folder for kvpnc."));
                    appendLogEntry(i18n("Unable to open wallet folder for kvpnc."), KVpncEnum::error);
                }
            }
            if ((useKwallet && KWallet::Wallet::isEnabled() && firstUseOfKwallet) || !kwalletOpened || !useKwallet || !KWallet::Wallet::isEnabled()) {
                // read from config file
                UserPassword = configgroup.readEntry("User password", "");
                PrivateKeyPass = configgroup.readEntry("PrivateKey password", "");
                PreSharedKey = configgroup.readEntry("Pre shared key", "");
                if (useKwallet && KWallet::Wallet::isEnabled() && firstUseOfKwallet)  {
                    if (KvpncDebugLevel > 2)
                        appendLogEntry(i18n("Wallet enabled and available, but for the first time, reading passwords from config file."), KVpncEnum::debug);
                }
                else {
                    appendLogEntry(i18n("Wallet disabled or not available, reading passwords from config file."), KVpncEnum::debug);
                }
            }

            VpnAccountData::ConnectionType ConnType = VpnAccountData::ConnectionType(VpnAccountData::cisco);
            QString type_string = configgroup.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 if (type_string == "vtun")
                ConnType = VpnAccountData::vtun;
            else if (type_string == "ssh")
                ConnType = VpnAccountData::ssh;
			else if ( type_string == "l2tpd_plain" )
				ConnType = VpnAccountData::l2tpd_plain;
            else
                ConnType = VpnAccountData::other;

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

            data->setDoPingIP(QVariant(configgroup.readEntry("do ping ip", false)).toBool());
            data->setPingHostIP(configgroup.readEntry("Ping host IP", ""));
            data->setUseSpecialRemoteID(QVariant(configgroup.readEntry("Use special remote ID", false)).toBool());
            data->setUseSpecialLocalID(QVariant(configgroup.readEntry("Use special local ID", false)).toBool());
            data->setSpecialRemoteID(configgroup.readEntry("Special remote ID", ""));
            data->setSpecialLocalID(configgroup.readEntry("Special local ID", ""));
            data->setLocalIDType(configgroup.readEntry("Local ID type", "asn1dn"));
            data->setRemoteIDType(configgroup.readEntry("Remote ID type", "none"));
            data->setUseSpecialServerCertificate(QVariant(configgroup.readEntry("Use special server certificate", false)).toBool());
            data->setSpecialServerCertificate(configgroup.readEntry("Special server certificate", ""));
            data->setUseUdp(QVariant(configgroup.readEntry("Use UDP-protocol", false)).toBool());
            data->setUseUdpPort(QVariant(configgroup.readEntry("Use UDP-port", false)).toBool());
            data->setUdpPort(QVariant(configgroup.readEntry("local UDP port", 4500)).toInt());
            data->setUseDnsUpdate(QVariant(configgroup.readEntry("use DNS_UPDATE", true)).toBool());
            data->setUseDnsServer(QVariant(configgroup.readEntry("use DNS-server", false)).toBool());
            data->setDnsServer(configgroup.readEntry("DNS server", ""));
            data->setRefuse40BitEncryption(QVariant(configgroup.readEntry("refuse 40 bit encryption", true)).toBool());
            data->setRefuse128BitEncryption(QVariant(configgroup.readEntry("refuse 128 bit encryption", false)).toBool());
            data->setAllowStatefulMode(QVariant(configgroup.readEntry("require stateless encryption", false)).toBool());
            data->setRequireMppe(QVariant(configgroup.readEntry("require mppe", true)).toBool());
            data->setUseNoBsdComp(QVariant(configgroup.readEntry("Use no BSD compression", true)).toBool());
            data->setUseNoIpDefault(QVariant(configgroup.readEntry("Do not use no IP by default", false)).toBool());
            data->setUseNoDeflate(QVariant(configgroup.readEntry("Use no deflate", true)).toBool());
            data->setDisableMPPEComp(QVariant(configgroup.readEntry("Disable MPPE compression", false)).toBool());
            data->setLocalVirtualIP(configgroup.readEntry("Local virtual IP", ""));
            data->setRemoteVirtualIP(configgroup.readEntry("Remote virtual IP", ""));
            data->setPreSharedKeyFile(configgroup.readEntry("Pre shared key file", ""));
            data->setExecuteCmdBeforeConnect(QVariant(configgroup.readEntry("Execute command before connect", false)).toBool());
            data->setExecuteCmdAfterConnect(QVariant(configgroup.readEntry("Execute command after connect", false)).toBool());
            data->setExecuteCmdBeforeDisconnect(QVariant(configgroup.readEntry("Execute command before disconnect", false)).toBool());
            data->setExecuteCmdAfterDisconnect(QVariant(configgroup.readEntry("Execute command after disconnect", false)).toBool());
            data->setCommandBeforeConnect(configgroup.readEntry("Command before connect", ""));
            data->setCommandAfterConnect(configgroup.readEntry("Command after connect", ""));
            data->setCommandBeforeDisconnect(configgroup.readEntry("Command before disconnect", ""));
            data->setCommandAfterDisconnect(configgroup.readEntry("Command after disconnect", ""));
            data->setReplaceDefaultRoute(QVariant(configgroup.readEntry("Replace default route", false)).toBool());
            data->setUseMtu(QVariant(configgroup.readEntry("Use own MTU", false)).toBool());
            data->setUseMru(QVariant(configgroup.readEntry("Use own MRU", false)).toBool());
            data->setMtu(QVariant(configgroup.readEntry("MTU for pppd", 1492)).toInt());
            data->setMru(QVariant(configgroup.readEntry("MRU for pppd", 1492)).toInt());
            data->setUseVirtualIP(QVariant(configgroup.readEntry("Use virtual IP", false)).toBool());
            data->setVirtualIP(configgroup.readEntry("Virtual IP", ""));
            data->setPskIsInFile(QVariant(configgroup.readEntry("PSK is in file", false)).toBool());
            data->setUseAdditionalNetworkRoutes(QVariant(configgroup.readEntry("Use additional network routes", false)).toBool());

            QString AdditionalNetworkRoutesString = configgroup.readEntry("Additional network routes", "");
            // Networks delimited by a ','
            QStringList AdditionalNetworkRoutes(AdditionalNetworkRoutesString.split(QString(",")));
            data->setAdditionalNetworkRoutes(AdditionalNetworkRoutes);
            data->setHashAlgo(configgroup.readEntry("Hash algorithm", "md5"));
            data->setEncryptionAlgorithm(configgroup.readEntry("Encryption algorithm", "3des"));
            data->setAuthenticationAlgorithm(configgroup.readEntry("Authentication algorithm", "hmac_sha1"));
            data->setTunnelDeviceType(configgroup.readEntry("Tunnel device type", "tun"));
            data->setUseUserdefinedPort(QVariant(configgroup.readEntry("Use userdefined port", false)).toBool());
            data->setUserdefinedPort(QVariant(configgroup.readEntry("Userdefined port", 1194)).toInt());
            data->setNsCertType(configgroup.readEntry("NS cert type", "client"));
            data->setUseNsCertType(QVariant(configgroup.readEntry("Use NS cert type", false)).toBool());
            data->setUseConnectionStatusCheck(QVariant(configgroup.readEntry("Use connection status check", true)).toBool());
            data->setConnectionStatusCheckSuccessCount(QVariant(configgroup.readEntry("Connection check success count", 4)).toInt());
            data->setConnectionStatusInterval(QVariant(configgroup.readEntry("Connection check status interval", 1)).toInt());
            data->setDoReconnectAfterConnectionLost(QVariant(configgroup.readEntry("Do reconnect after connection lost", false)).toBool());
            data->setDisableLzoCompression(QVariant(configgroup.readEntry("Disable LZO compression", true)).toBool());
            data->setUserPassword(UserPassword);
            data->setRemoteNetAddr(configgroup.readEntry("Remote net address", ""));
            data->setRemoteNetMask(QString().setNum(QVariant(configgroup.readEntry("Remote net mask", 24)).toInt()));
            data->setPreSharedKey(PreSharedKey);
            data->setPrivateKeyPass(PrivateKeyPass);
            data->setAuthWithUsernameAndPassword(QVariant(configgroup.readEntry("AuthWithUsernameAndPassword", false)).toBool());
            data->setAllowEmptyGroupPassword(QVariant(configgroup.readEntry("AllowEmptyGroupPassword", false)).toBool());
            data->setUseUserdefiniedCipher(QVariant(configgroup.readEntry("Use userdefinied cipher", false)).toBool());
            data->setUserdefiniedCipher(configgroup.readEntry("Userdefinied cipher", ""));
            data->setUseRedirectGateway(QVariant(configgroup.readEntry("Use redirect gateway", false)).toBool());
            data->setUseTlsAuth(QVariant(configgroup.readEntry("Use TLS auth", false)).toBool());
            data->setTlsAuthFile(configgroup.readEntry("TLS auth file", ""));
            data->setUseHttpProxy(QVariant(configgroup.readEntry("Use HTTP proxy", false)).toBool());
            data->setHttpProxy(configgroup.readEntry("HTTP proxy host", ""));
            data->setHttpProxyPort(QVariant(configgroup.readEntry("HTTP proxy port", 8080)).toInt());
            data->setHttpProxyTimeout(QVariant(configgroup.readEntry("HTTP proxy timeout", 5)).toInt());
            data->setDontSaveUsername(QVariant(configgroup.readEntry("Dont save username", false)).toBool());
            data->setUseModeConfig(QVariant(configgroup.readEntry("Use mode config", false)).toBool());
            data->setExchangeMode(configgroup.readEntry("Exchange mode", "main"));
            data->setUseReconnectDelay(QVariant(configgroup.readEntry("Use delay at reconnect", false)).toBool());
            data->setReconnectDelay(QVariant(configgroup.readEntry("Reconnect delay", 5)).toInt());
            data->setUseTlsRemoteHost(QVariant(configgroup.readEntry("Use TLS host", false)).toBool());
            data->setTlsRemoteHost(configgroup.readEntry("TLS remote host", ""));
            data->setDisableOpportunisticEncryption(QVariant(configgroup.readEntry("Disable opportunistic encryption", false)).toBool());
            data->setRightNextHop(configgroup.readEntry("Right next hop", ""));
            data->setLeftNextHop(configgroup.readEntry("Left next hop", ""));
            data->setUseMssfix(QVariant(configgroup.readEntry("Use userdef packet size", false)).toBool());
            data->setUseFragment(QVariant(configgroup.readEntry("Use userdefinied packet size for fragmentation" , false)).toBool());
            data->setMssfix(QVariant(configgroup.readEntry("Mssfix", 1300)).toInt());
            data->setFragment(QVariant(configgroup.readEntry("Fragment", 1300)).toInt());
            data->setPeerTimeout(QVariant(configgroup.readEntry("PeerTimeout", 5)).toInt());
            data->setDisableCcp(QVariant(configgroup.readEntry("Disable CCP", true)).toBool());
            data->setUseSmartcard(QVariant(configgroup.readEntry("Use smartcard", false)).toBool());
            data->setUseXauthInteractive(QVariant(configgroup.readEntry("Use Xauth interactive", false)).toBool());
            data->setUseHttpProxyAuth(QVariant(configgroup.readEntry("Use HTTP Proxy Authentication", false)).toBool());
            data->setHttpProxyAuthType(configgroup.readEntry("HTTP Proxy Authtype", "basic"));
            data->setHttpProxyUser(configgroup.readEntry("HTTP Proxy Auth user", ""));
            data->setHttpProxyPass(configgroup.readEntry("HTTP Proxy Auth pass", ""));
            data->setUseOnlyCaCertAndUserAuth(QVariant(configgroup.readEntry("Use only CA cert and user auth", false)).toBool());
            data->setUseMailAddressAsIdentifier(QVariant(configgroup.readEntry("Use mail address as identifier", false)).toBool());
            data->setUseRightNextHop(QVariant(configgroup.readEntry("Use right next hop", false)).toBool());
            data->setUseLeftNextHop(QVariant(configgroup.readEntry("Use left next hop", false)).toBool());
            data->setPkcs11Providers(configgroup.readEntry("Pkcs11 providers", "/usr/local/lib/libetpkcs11.so"));
            data->setPkcs11SlotType(configgroup.readEntry("Pkcs11 slot type", "id"));
            data->setPkcs11Slot(configgroup.readEntry("Pkcs11 slot", "0"));
            data->setPkcs11IdType(configgroup.readEntry("Pkcs11 id type", "id"));
            data->setPkcs11Id(configgroup.readEntry("Pkcs11 id", ""));
            data->setPkcs11SignMode(configgroup.readEntry("Pkcs11 sign mode", "auto"));
            data->setUsePkcs11Providers(QVariant(configgroup.readEntry("Use Pkcs11 providers", false)).toBool());
            data->setAllowEmptyPrivateKeyPassword(QVariant(configgroup.readEntry("Allow empty private key password", false)).toBool());
            data->setAllowIpAddressChangeOfPeer(QVariant(configgroup.readEntry("Allow ip address change of peer", false)).toBool());
            data->setAuthMethod(configgroup.readEntry("Auth method", "chap"));
            data->setCommandAfterConnectDelayTime(QVariant(configgroup.readEntry("Command after connect delay time", 5)).toInt());
            data->setUseSearchDomainInResolvConf(QVariant(configgroup.readEntry("Use search domain in resolv conf", false)).toBool());
            data->setSearchDomainInResolvConf(configgroup.readEntry("Search domain in resolv conf", ""));
            data->setAuthenticationDirection(configgroup.readEntry("Authentication direction", "none"));
            data->setCiscoNatMode(configgroup.readEntry("CiscoNatMode", "natt"));
            data->setIpsecEsp(configgroup.readEntry("IPSec ESP", "3des-md5-96"));
            data->setIpsecIke(configgroup.readEntry("IPSec IKE", "3des-sha-modp2048"));
            data->setVtunProfile(configgroup.readEntry("Vtun profile", ""));
            data->setDisableDataEncryption(QVariant(configgroup.readEntry("Disable data encryption", false)).toBool());
            data->setUseAuthenticationAlgorithm(QVariant(configgroup.readEntry("Use authentication algorithm", false)).toBool());
            data->setFixPathMtuDiscoveryProblem(QVariant(configgroup.readEntry("Fix path mtu discovery problem" , false)).toBool());
            data->setUseRemoteNetwork(QVariant(configgroup.readEntry("Use remote network", false)).toBool());
            data->setIpsecVpnMode(configgroup.readEntry("Ipsec vpn mode", "tunnel"));
            data->setDisableHeaderCompression(QVariant(configgroup.readEntry("DisableHeaderCompression", false)).toBool());
            data->setDisableMagicNumberNegotiation(QVariant(configgroup.readEntry("DisableMagicNumberNegotiation", false)).toBool());
            data->setDisableIpx(QVariant(configgroup.readEntry("DisableIpx", false)).toBool());
            data->setDisableProtocolFieldCompression(QVariant(configgroup.readEntry("Disable protocol field compression", false)).toBool());
            data->setDisableAddressControlCompression(QVariant(configgroup.readEntry("Disable address control compression", false)).toBool());
            data->setUseCustomIke(QVariant(configgroup.readEntry("Use custom ike", false)).toBool());
            data->setUseCustomEsp(QVariant(configgroup.readEntry("Use custom esp", false)).toBool());
            data->setVerifyCaCert(QVariant(configgroup.readEntry("Verify ca cert", true)).toBool());
            data->setUseDpdIdleTimeout(QVariant(configgroup.readEntry("Use DPD idle timeout", false)).toBool());
            data->setDpdIdleTimeout(QVariant(configgroup.readEntry("DPD idle timeout", 300)).toInt());
            data->setHideGroupPasswordInAccountDataDialog(QVariant(configgroup.readEntry("Hide group password in accountdata dialog", false)).toBool());
            data->setMaxConnectTries(QVariant(configgroup.readEntry("MaxConnectTries", 300)).toInt());
            data->setL2tpDaemon((VpnAccountData::L2tpDaemonType) QVariant(configgroup.readEntry("L2tpDaemon", 0)).toInt());
            data->setUseLeftSourceIp(QVariant(configgroup.readEntry("UseLeftSourceIp", false)).toBool());
            data->setUseRightSourceIp(QVariant(configgroup.readEntry("UseRightSourceIp", false)).toBool());
            data->setLeftSourceIp(configgroup.readEntry("LeftSourceIp", ""));
            data->setRightSourceIp(configgroup.readEntry("RightSourceIp", ""));
            data->setUseVirtualSubnetworks(QVariant(configgroup.readEntry("Use virtual subnets", false)).toBool());
            data->setVirtualSubnetworks(configgroup.readEntry("Virtual subnets", ""));
            data->setDisablePushFromServer(QVariant(configgroup.readEntry("DisablePushFromServer", false)).toBool());
            data->setDisableBind(QVariant(configgroup.readEntry("DisableBind", false)).toBool());
            data->setUseRenegSec(QVariant(configgroup.readEntry("UseRenegSec", false)).toBool());
            data->setRenegSec(QVariant(configgroup.readEntry("RenegSec", 3600)).toInt());
            data->setUseTunnelPing(QVariant(configgroup.readEntry("UseTunnelPing", false)).toBool());
            data->setTunnelPing(QVariant(configgroup.readEntry("TunnelPing", 10)).toInt());
            data->setUseTunnelPingRestart(QVariant(configgroup.readEntry("UseTunnelPingRestart", false)).toBool());
            data->setTunnelPingRestart(QVariant(configgroup.readEntry("TunnelPingRestart", 120)).toInt());
            data->setRequireEap(QVariant(configgroup.readEntry("RequireEap", false)).toBool());
            data->setUseSshConfigRemoteScript(QVariant(configgroup.readEntry("UseSshConfigRemoteScript", false)).toBool());
            data->setSshConfigRemoteScript(configgroup.readEntry("SshConfigRemoteScript", ""));
            data->setAskUserPasswordOnEachConnect(QVariant(configgroup.readEntry("AskUserPasswordOnEachConnect", false)).toBool());
            data->setUseCiscoCertStore( QVariant(configgroup.readEntry("UseCiscoCertStore", false)).toBool());
            data->setUseNat(QVariant(configgroup.readEntry("UseNat", true)).toBool());

            if (useKwallet && KWallet::Wallet::isEnabled() && firstUseOfKwallet && kwalletOpened)  {
                if (KvpncDebugLevel > 2)
                    appendLogEntry(i18n("Wallet enabled and available, but for the first time, writing passwords to wallet..."), KVpncEnum::debug);
                if (wallet != 0) {
                    QString walletname = "kvpnc";

                    if (!wallet->hasFolder(walletname)) {
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Folder for kvpnc has been created."), KVpncEnum::debug);
                        wallet->createFolder(walletname);
                    }

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

                        bool UserPasswordOK = true;
                        if (data->getSaveUserPassword())
                            UserPasswordOK = (wallet->writePassword(QString(name + "__user_pw"), data->getUserPassword()) == 0);
                        else
                            UserPasswordOK = (wallet->writePassword(QString(name + "__user_pw"), "") == 0);
                        //wallet->sync();

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

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

                        if (UserPasswordOK) {
                            if (KvpncDebugLevel > 2) {
                                appendLogEntry(i18n("Writing %1 was successful.", i18n("user password")), KVpncEnum::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?" , QString(i18n("user password"))),
                                //		i18n( "Unable to store secure %1" , QString(i18n("user password"))),
                                //		KGuiItem( i18n( "Store &Unsafe" ), QLatin1String( "unlock" ),QString::fromLatin1( "KWalletFallbackToKConfig" ) ) ) == KMessageBox::Continue ) {
                                //		configgroup.writeEntry( "User password", it->getUserPassword() );
                                //}

                                appendLogEntry(i18n("Writing %1 has failed.", i18n("user password")), KVpncEnum::error);
                            }
                        }

                        if (PskOK) {
                            if (KvpncDebugLevel > 2) {
                                appendLogEntry(i18n("Writing %1 was successful.",
                                                    i18n("preshared key")),
                                               KVpncEnum::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?", QString(i18n("pre shared key"))),
                                //	i18n( "Unable to store secure %1" , QString(i18n("pre shared key"))),
                                //	KGuiItem( i18n( "Store &Unsafe" ), QLatin1String( "unlock" ),QString::fromLatin1( "KWalletFallbackToKConfig" ) ) ) == KMessageBox::Continue ) {
                                //	configgroup.writeEntry( "Pre shared key", it->getPreSharedKey() );
                                //}
                                appendLogEntry(i18n("Writing %1 has failed.", i18n("preshared key")), KVpncEnum::error);
                            }
                        }

                        if (PskKeyPassOK) {
                            if (KvpncDebugLevel > 2) {
                                appendLogEntry(i18n("Writing %1 was successful.", i18n("preshared key password")), KVpncEnum::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?" , QString(i18n("preshared key password"))),
                                //	i18n( "Unable to store secure %1" , QString(i18n("reshared key password"))),
                                //	KGuiItem( i18n( "Store &Unsafe" ), QLatin1String( "unlock" ),QString::fromLatin1( "KWalletFallbackToKConfig" ) ) ) == KMessageBox::Continue ) {
                                //	configgroup.writeEntry( "Pre shared key", it->getPreSharedKey() );
                                //}
                                appendLogEntry(i18n("Writing %1 has failed.", i18n("preshared key password")),KVpncEnum::error);
                            }
                        }

                        wallet->sync();
                    }
                }
            }

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

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

            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."), KVpncEnum::info);

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

            if (appPointer->hasPendingEvents())
                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."), KVpncEnum::debug);
    }
}

void KVpncConfig::checkStandardPathValues()
{
    if (pathToVpnc.isEmpty())
        pathToVpnc = "/usr/sbin/vpnc";

    if (pathToCiscoVpnc.isEmpty())
        pathToCiscoVpnc = "/usr/local/bin/vpnclient";

    if (pathToSetkey.isEmpty())
        pathToSetkey = "/usr/sbin/setkey";

    if (pathToRacoon.isEmpty())
        pathToRacoon = "/usr/sbin/racoon";

    if (pathToRacoonctl.isEmpty())
        pathToRacoonctl = "/usr/sbin/racoonctl";

    if (pathToIptables.isEmpty())
        pathToIptables = "/sbin/iptables";

    if (pathToOpenssl.isEmpty())
        pathToOpenssl = "/usr/bin/openssl";

    if (pathToIpsec.isEmpty())
        pathToIpsec = "/usr/sbin/ipsec";

    if (pathToIp.isEmpty())
        pathToIp = "/sbin/ip";

    if (pathToIfconfig.isEmpty())
        pathToIfconfig = "/sbin/ifconfig";

    if (pathToRoute.isEmpty())
        pathToRoute = "/sbin/route";

    if (pathToNetstat.isEmpty())
        pathToNetstat = "/bin/netstat";

    if (pathToPppd.isEmpty())
        pathToPppd = "/usr/sbin/pppd";

    if (pathToPptp.isEmpty())
        pathToPptp = "/usr/sbin/pptp";

    if (pathToL2tpd.isEmpty())
        pathToL2tpd = "/usr/sbin/l2tpd";

    if (pathToXl2tpd.isEmpty())
        pathToXl2tpd = "/usr/sbin/xl2tpd";

    if (pathToOpenl2tp.isEmpty())
        pathToOpenl2tp = "/usr/sbin/openl2tpd";

    if (pathToKill.isEmpty())
        pathToKill = "/bin/kill";

    if (pathToKillall.isEmpty())
        pathToKillall = "/usr/bin/killall";

    if (pathToPing.isEmpty())
        pathToPing = "/bin/ping";

    if (pathToOpenvpn.isEmpty())
        pathToOpenvpn = "/usr/sbin/openvpn";

    if (pathToPkcs11Tool.isEmpty())
        pathToPkcs11Tool = "/usr/bin/pkcs11-tool";

    if (pathToVtund.isEmpty())
        pathToVtund = "/usr/sbin/vtund";

    if (pathToCiscoCertMgr.isEmpty())
        pathToCiscoCertMgr = "/usr/local/bin/cisco_cert_mgr";

    if (pathToTail.isEmpty())
        pathToTail = "/usr/bin/tail";

    if (pathToSsh.isEmpty())
        pathToSsh = "/usr/bin/ssh";

    if (pathToKsshAskpass.isEmpty())
        pathToKsshAskpass = "/usr/bin/ksshaskpass";

    if (pathToGnomeSshAskpass.isEmpty())
        pathToGnomeSshAskpass = "/usr/lib/openssh/gnome-ssh-askpass";


}

bool KVpncConfig::exportKvpncConfig(QString filename)
{
    bool ok = true;
    int exportCount = 0;
    bool exportGlobal = false;
    QFile exportfile(filename);
    if (exportfile.exists()) {
        int res = KMessageBox::questionYesNo((QWidget *) 0, i18n("\"%1\" still exists. Do you really want to overwrite it?" ,   filename), i18n("&Overwrite") , KStandardGuiItem::cancel());

        if (res == 4)
            ok = false;
    }
    if (ok == true) {
        if (exportfile.open(QIODevice::WriteOnly)) {
            QList<VpnAccountData *> *exportAccountList = new QList<VpnAccountData *>();
            KvpncImportProfileSelectionDialog selectdlg(0);
            VpnAccountData *it = NULL;
            selectdlg.OpenProfileManagerCheckBox->hide();

            selectdlg.textLabel->setText(i18n("Select profiles for export:"));
            selectdlg.setButtonText(KDialog::Apply, i18n("&Export selected profiles..."));
            selectdlg.ImportGlobalSettingsCheckBox->setText(i18n("Export &global settings"));

            if (!AccountList->isEmpty()) {
                selectdlg.ImportProfileListView->setColumnCount(3);
                QStringList LabelList;
                LabelList << i18n("Name") << i18n("Type") << i18n("Gateway");
                selectdlg.ImportProfileListView->setHeaderLabels(LabelList);

                VpnAccountData *it;
                QList<QTreeWidgetItem *> items;
                QStringList values;
                for (int accountIdx = 0; accountIdx < AccountList->size(); ++accountIdx) {
                    it = AccountList->at(accountIdx);
                    QString name = it->getName();
                    QString type;
                    if (it->getConnectionType() == VpnAccountData::cisco)
                        type = "cisco" ;
                    else if (it->getConnectionType() == VpnAccountData::ciscoorig)
                        type = "ciscoorig" ;
                    else if (it->getConnectionType() == VpnAccountData::racoon)
                        type = "racoon" ;
                    else if (it->getConnectionType() == VpnAccountData::l2tpd_racoon)
                        type = "l2tpd (racoon)" ;
                    else if (it->getConnectionType() == VpnAccountData::freeswan)
                        type = "freeswan" ;
                    else if (it->getConnectionType() == VpnAccountData::l2tpd_freeswan)
                        type = "l2tpd (openswan)" ;
                    else if (it->getConnectionType() == VpnAccountData::pptp)
                        type = "pptp" ;
                    else if (it->getConnectionType() == VpnAccountData::openvpn)
                        type = "openvpn" ;
                    else if (it->getConnectionType() == VpnAccountData::vtun)
                        type = "vtun" ;
                    else if (it->getConnectionType() == VpnAccountData::ssh)
                        type = "ssh" ;
					else if ( it->getConnectionType() == VpnAccountData::l2tpd_plain )
						type = "l2tpd_plain" ;
                    else
                        type =  i18n("other");

                    values << name << type << it->getGateway();

                    QTreeWidgetItem *listitem = new QTreeWidgetItem((QTreeWidget*)0, values);
                    listitem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
                    listitem->setData(0, Qt::CheckStateRole, Qt::Unchecked);
                    items.append(listitem);
                    values.clear();
                }
                selectdlg.ImportProfileListView->insertTopLevelItems(0, items);
            }
            bool ret = selectdlg.exec();
            if (ret == true) {
                QTreeWidgetItemIterator it2(selectdlg.ImportProfileListView);
                while (*it2) {
                    VpnAccountData *data = NULL;
                    it = 0;
                    for (int accountIdx = 0; accountIdx < AccountList->size(); ++accountIdx) {
                        it = AccountList->at(accountIdx);
                        if (it->getName() == (*it2)->text(0) && (*it2)->data(0, Qt::CheckStateRole).toInt() == Qt::Checked) {
                            data = it;
                            exportAccountList->append(data);
                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Profile marked for export: %1", it->getName()) , KVpncEnum::debug);
                            break;
                        }
                    }
                    ++it2;
                }
                exportGlobal = selectdlg.ImportGlobalSettingsCheckBox->isChecked();
                if (exportAccountList->count() == 0 && exportGlobal == false) {
                    KMessageBox::sorry(0, i18n("No profiles for export, export canceled."));
                    exportfile.close();
                    exportfile.remove();
                    return false;
                }
            } else {
                KMessageBox::sorry(0, i18n("Export canceled."));
                exportfile.close();
                exportfile.remove();
                return false;
            }



            QString date(__DATE__);
            QString day = date.section(' ', 0, 0);
            QString month = QString().setNum(QDate::fromString(date.section(' ', 0, 0), Qt::ISODate).month());
            QString year = date.section(' ', 2, 2);

            QString currentdate ( date+" "+ QTime().currentTime().toString( "hh:mm" ) );

            QTextStream ExportStream(&exportfile);
            ExportStream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << "\n";
            ExportStream << "<!-- generated by kvpnc at " << currentdate << ". Do not edit it. -->" << "\n";
            ExportStream << "<kvpnc>" << "\n";
            ExportStream << "\t<version>" << "\n";
            ExportStream << "\t\t<app>" << "0.9.2" << "</app>" << "\n";
            ExportStream << "\t\t<exportversion>" << "1" << "</exportversion>" << "\n";
            ExportStream << "\t</version>" << "\n";

            if (exportGlobal == true) {
                ExportStream << "\t<global>" << "\n";
                ExportStream << "\t\t<option name=\"Minimize after connect\"" << " type=\"bool\"" << ">" << minimizeAfterConnect << "</option>\n";
                ExportStream << "\t\t<option name=\"Hide on startup\"" << " type=\"bool\"" << ">" << hideMainWindow << "</option>\n";
                ExportStream << "\t\t<option name=\"Use silent quit\"" << " type=\"bool\"" << ">" << useSilentQuit << "</option>\n";
                ExportStream << "\t\t<option name=\"Dont quit on CloseEvent\"" << " type=\"bool\"" << ">" << dontQuitOnCloseEvent << "</option>\n";
                ExportStream << "\t\t<option name=\"Enable pppd debug\"" << " type=\"bool\"" << ">" << enableDebugPppd << "</option>\n";
                ExportStream << "\t\t<option name=\"Enable pptpd debug\"" << " type=\"bool\"" << ">" << enableDebugPptpd << "</option>\n";
                ExportStream << "\t\t<option name=\"Enable l2tpd debug\"" << " type=\"bool\"" << ">" << enableDebugL2tpd << "</option>\n";
                ExportStream << "\t\t<option name=\"Enable xl2tpd debug\"" << " type=\"bool\"" << ">" << enableDebugXl2tpd << "</option>\n";
                ExportStream << "\t\t<option name=\"Enable openl2tp debug\"" << " type=\"bool\"" << ">" << int (enableDebugOpenl2tp) << "</option>\n";
                ExportStream << "\t\t<option name=\"Enable FreeSWAN verbose\"" << " type=\"bool\"" << ">" << enableFreeswanVerbose << "</option>\n";
                ExportStream << "\t\t<option name=\"Pluto Debug\"" << " type=\"stringlist\"" << ">" << PlutoDebug.join(" ") << "</option>\n";
                ExportStream << "\t\t<option name=\"Klips Debug\"" << " type=\"stringlist\"" << ">" << KlipsDebug.join(" ") << "</option>\n";
                ExportStream << "\t\t<option name=\"Show debugconsole\"" << " type=\"bool\"" << ">" << showDebugConsole << "</option>\n";
                ExportStream << "\t\t<option name=\"Pid file for vpnc \"" << " type=\"string\"" << ">" << Vpnc_pid_file << "</option>\n";
                ExportStream << "\t\t<option name=\"Vpnc debuglevel\"" << " type=\"int\"" << ">" << VpncDebugLevel << "</option>\n";
                ExportStream << "\t\t<option name=\"Racoon debuglevel\"" << " type=\"string\"" << ">" << RacoonDebugLevel << "</option>\n";
                ExportStream << "\t\t<option name=\"Kvpnc debuglevel\"" << " type=\"int\"" << ">" << KvpncDebugLevel << "</option>\n";
                ExportStream << "\t\t<option name=\"Pppd debuglevel\"" << " type=\"bool\"" << ">" << PppdDebugLevel << "</option>\n";
                ExportStream << "\t\t<option name=\"Pppd kernel log level\"" << " type=\"int\"" << ">" << PppdKernelLogLevel << "</option>\n";
                ExportStream << "\t\t<option name=\"Openvpn debuglevel\"" << " type=\"int\"" << ">" << OpenvpnDebugLevel << "</option>\n";
                ExportStream << "\t\t<option name=\"Pptp debuglevel\"" << " type=\"string\"" << ">" << PptpLogLevel << "</option>\n";
                ExportStream << "\t\t<option name=\"Ssh debuglevel\"" << " type=\"string\"" << ">" << SshDebugLevel << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to vpnc-bin\"" << " type=\"string\"" << ">" << pathToVpnc << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to vpnclient\"" << " type=\"string\"" << ">" << pathToCiscoVpnc << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to racoon\"" << " type=\"string\"" << ">" << pathToRacoon << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to racoonctl\"" << " type=\"string\"" << ">" << pathToRacoonctl << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to setkey\"" << " type=\"string\"" << ">" << pathToSetkey << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to iptables\"" << " type=\"string\"" << ">" << pathToIptables << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to openssl\"" << " type=\"string\"" << ">" << pathToOpenssl << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to freeswan\"" << " type=\"string\"" << ">" << pathToIpsec << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to pppd\"" << " type=\"string\"" << ">" << pathToPppd << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to pptp\"" << " type=\"string\"" << ">" << pathToPptp << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to l2tpd\"" << " type=\"string\"" << ">" << pathToL2tpd << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to xl2tpd\"" << " type=\"string\"" << ">" << pathToXl2tpd << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to openl2tp\"" << " type=\"string\"" << ">" << pathToOpenl2tp << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to kill\"" << " type=\"string\"" << ">" << pathToKill << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to kill-all\"" << " type=\"string\"" << ">" << pathToKillall << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to ping\"" << " type=\"string\"" << ">" << pathToPing << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to openvpn\"" << " type=\"string\"" << ">" << pathToOpenvpn << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to iputility\"" << " type=\"string\"" << ">" << pathToIp << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to ifconfig\"" << " type=\"string\"" << ">" << pathToIfconfig << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to route\"" << " type=\"string\"" << ">" << pathToRoute << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to netstat\"" << " type=\"string\"" << ">" << pathToNetstat << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to pkcs11-tool\"" << " type=\"string\"" << ">" << pathToPkcs11Tool << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to vtund\"" << " type=\"string\"" << ">" << pathToVtund << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to cisco_cert_mgr\"" << " type=\"string\"" << ">" << pathToCiscoCertMgr << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to tail\"" << " type=\"string\"" << ">" << pathToTail << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to ssh\"" << " type=\"string\"" << ">" << pathToSsh << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to ksshaskpass\"" << " type=\"string\"" << ">" << pathToKsshAskpass << "</option>\n";
                ExportStream << "\t\t<option name=\"Path to ssh-askpass-gnome\"" << " type=\"string\"" << ">" << pathToGnomeSshAskpass << "</option>\n";
                ExportStream << "\t\t<option name=\"Show Statusbar\"" << " type=\"bool\"" << ">" << showStatusBar << "</option>\n";
                ExportStream << "\t\t<option name=\"Try connect timeout\"" << " type=\"int\"" << ">" << tryConnectTimeout << "</option>\n";
                ExportStream << "\t\t<option name=\"Last Profile\"" << " type=\"string\"" << ">" << lastProfile << "</option>\n";
                ExportStream << "\t\t<option name=\"Write log file\"" << " type=\"bool\"" << ">" << writeLogFile << "</option>\n";
                ExportStream << "\t\t<option name=\"Hold generated scripts\"" << " type=\"bool\"" << ">" << holdGeneratedScripts << "</option>\n";
                ExportStream << "\t\t<option name=\"Programs in path\"" << " type=\"bool\"" << ">" << programsInPath << "</option>\n";
                ExportStream << "\t\t<option name=\"Info logwindow color\"" << " type=\"string\"" << ">" << InfoLogColor.name() << "</option>\n";
                ExportStream << "\t\t<option name=\"Remote logwindow color\"" << " type=\"string\"" << ">" << RemoteLogColor.name() << "</option>\n";
                ExportStream << "\t\t<option name=\"Error logwindow color\"" << " type=\"string\"" << ">" << ErrorLogColor.name() << "</option>\n";
                ExportStream << "\t\t<option name=\"Success  logwindow color\"" << " type=\"string\"" << ">" << SuccessLogColor.name() << "</option>\n";
                ExportStream << "\t\t<option name=\"Debug logwindow color\"" << " type=\"string\"" << ">" << DebugLogColor.name() << "</option>\n";
                ExportStream << "\t\t<option name=\"Debug background color\"" << " type=\"string\"" << ">" << DebugBackgroundcolor.name() << "</option>\n";
                ExportStream << "\t\t<option name=\"Use colorized log output\"" << " type=\"bool\"" << ">" << useColorizedLogOutput << "</option>\n";
                ExportStream << "\t\t<option name=\"Show interface IP in tooltip\"" << " type=\"bool\"" << ">" << showInterfaceIPinTooltip << "</option>\n";
                ExportStream << "\t\t<option name=\"Auto connect profile\"" << " type=\"string\"" << ">" << AutoConnectProfile << "</option>\n";
                ExportStream << "\t\t<option name=\"Do auto connect at startup\"" << " type=\"bool\"" << ">" << doAutoConnectAtStartup << "</option>\n";
                ExportStream << "\t\t<option name=\"Log viewer font size\"" << " type=\"int\"" << ">" << LogViewerFontSize << "</option>\n";
                ExportStream << "\t\t<option name=\"Mainwindow width\"" << " type=\"int\"" << ">" << parent->width() << "</option>\n";
                ExportStream << "\t\t<option name=\"Mainwindow height\"" << " type=\"int\"" << ">" << parent->height() << "</option>\n";
                ExportStream << "\t\t<option name=\"Mainwindow position x\"" << " type=\"int\"" << ">" << parent->x() << "</option>\n";
                ExportStream << "\t\t<option name=\"Mainwindow position y\"" << " type=\"int\"" << ">" << parent->y() << "</option>\n";
                ExportStream << "\t\t<option name=\"Openvpn management port\"" << " type=\"bool\"" << ">" << OpenvpnManagementPort << "</option>\n";
                ExportStream << "\t\t<option name=\"hideOnCloseInfo\"" << " type=\"bool\"" << ">" << hideOnCloseInfo << "</option>\n";
                //   ExportStream << "\t\t<option name=\"ToolBar Settings\"" << " type=\"bool\"" << ">" << parent->toolBar( "mainToolBar" )<< "</option>\n";
                ExportStream << "\t\t<option name=\"Use KWallet\"" << " type=\"bool\"" << ">" << useKwallet << "</option>\n";
                ExportStream << "\t\t<option name=\"FeedbackMailSent\"" << " type=\"bool\"" << ">" << feedbackMailSent << "</option>\n";
                ExportStream << "\t\t<option name=\"Do kill l2tpd if still running\"" << " type=\"bool\"" << ">" << doKillL2tpdIfStillRunning << "</option>\n";
                ExportStream << "\t\t<option name=\"Do kill xl2tpd if still running\"" << " type=\"bool\"" << ">" << doKillXl2tpdIfStillRunning << "</option>\n";
                ExportStream << "\t\t<option name=\"Do kill racoon if still running\"" << " type=\"bool\"" << ">" << doKillRacoonIfStillRunning << "</option>\n";
                ExportStream << "\t\t<option name=\"Show connection time in Tooltip\"" << " type=\"bool\"" << ">" << showConnectionTimeInTooltip << "</option>\n";
                ExportStream << "\t\t<option name=\"Enable debug Openvpn\"" << " type=\"bool\"" << ">" << enableDebugOpenvpn << "</option>\n";
                ExportStream << "\t\t<option name=\"EnableDebugXl2tpdNetwork\"" << " type=\"bool\"" << ">" << int (enableDebugXl2tpdNetwork);
                ExportStream << "\t\t<option name=\"EnableDebugXl2tpdpacket\"" << " type=\"bool\"" << ">" << int (enableDebugXl2tpdpacket);
                ExportStream << "\t\t<option name=\"EnableDebugXl2tpdstate\"" << " type=\"bool\"" << ">" << int (enableDebugXl2tpdstate);
                ExportStream << "\t\t<option name=\"EnableDebugXl2tpdtunnel\"" << " type=\"bool\"" << ">" << int (enableDebugXl2tpdtunnel);

                ExportStream << "\t</global>" << "\n";
            }


            ExportStream << "\t<profiles>" << "\n";
//    VpnAccountData *it;
            if (!exportAccountList->isEmpty()) {
                for (int i = 0; i < exportAccountList->count();i++) {
                    it = AccountList->at(i);
                    ExportStream << "\t\t<profile name=\"" << it->getName() << "\">" << "\n";

                    // normal config
                    if (it->getConnectionType() == VpnAccountData::cisco)
                        ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "cisco" << "</option>" << "\n";
                    else if (it->getConnectionType() == VpnAccountData::ciscoorig)
                        ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "ciscoorig" << "</option>" << "\n";
                    else if (it->getConnectionType() == VpnAccountData::racoon)
                        ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "racoon" << "</option>" << "\n";
                    else if (it->getConnectionType() == VpnAccountData::l2tpd_racoon)
                        ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "l2tpd (racoon)" << "</option>" << "\n";
                    else if (it->getConnectionType() == VpnAccountData::freeswan)
                        ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "freeswan" << "</option>" << "\n";
                    else if (it->getConnectionType() == VpnAccountData::l2tpd_freeswan)
                        ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "l2tpd (openswan)" << "</option>" << "\n";
                    else if (it->getConnectionType() == VpnAccountData::pptp)
                        ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "pptp" << "</option>" << "\n";
                    else if (it->getConnectionType() == VpnAccountData::openvpn)
                        ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "openvpn" << "</option>" << "\n";
					else if (it->getConnectionType() == VpnAccountData::l2tpd_plain )
						ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "l2tpd_plain" << "</option>" << "\n";
                    else
                        ExportStream << "\t\t\t<option name=\"Connection type\"" << " type=\"string\"" << ">" <<  "other" << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"VPN Gateway\"" << " type=\"string\"" << ">" <<  it->getGateway() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"VPN ID\"" << " type=\"string\"" << ">" <<  it->getID() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Username\"" << " type=\"string\"" << ">" <<  it->getUserName() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Save user password\"" << " type=\"bool\"" << ">" <<  it->getSaveUserPassword() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Save PSK\"" << " type=\"bool\"" << ">" <<  it->getSavePsk() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Save private key password\"" << " type=\"bool\"" << ">" <<  it->getSavePrivateKeyPassword() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Private key\"" << " type=\"string\"" << ">" <<  it->getPrivateKey() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use advanced settings\"" << " type=\"bool\"" << ">" <<  it->getUseAdvancedSettings() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Application version\"" << " type=\"string\"" << ">" <<  it->getApplicationVersion() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Local port\"" << " type=\"int\"" << ">" <<  it->getLocalPort() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Remote port\"" << " type=\"int\"" << ">" <<  it->getRemotePort() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"NT domain name\"" << " type=\"string\"" << ">" <<  it->getNtDomainName() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Perfect forward secrety\"" << " type=\"string\"" << ">" <<  it->getPerfectForwardSecrety() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"IKE group\"" << " type=\"string\"" << ">" <<  it->getIkeGroup() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use application version\"" << " type=\"bool\"" << ">" <<  it->getUseApplicationVersion() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use global IPSec secret\"" << " type=\"bool\"" << ">" <<  it->getUseGlobalIpsecSecret() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use IKE group\"" << " type=\"bool\"" << ">" <<  it->getUseIkeGroup() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use local port\"" << " type=\"bool\"" << ">" <<  it->getUseLocalPort() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use remote port\"" << " type=\"bool\"" << ">" <<  it->getUseRemotePort() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use NT domain name\"" << " type=\"bool\"" << ">" <<  it->getUseNtDomainName() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use single DES\"" << " type=\"bool\"" << ">" <<  it->getUseSingleDes() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use perfect Forward Secrety\"" << " type=\"bool\"" << ">" <<  it->getUsePerfectForwardSecrety() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Remote net address\"" << " type=\"string\"" << ">" <<  it->getRemoteNetAddr() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Remote net mask\"" << " type=\"string\"" << ">" <<  it->getRemoteNetMask() << "</option>" << "\n";

                    ExportStream << "\t\t\t<option name=\"x509 certificate\"" << " type=\"string\"" << ">" <<  it->getX509Certificate() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Ca certificate\"" << " type=\"string\"" << ">" <<  it->getCaCertificate() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Network device\"" << " type=\"string\"" << ">" <<  it->getNetworkDevice() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Cert path\"" << " type=\"string\"" << ">" <<  it->getCertPath() << "</option>" << "\n";
                    if (it->getAuthType() == VpnAccountData::cert)
                        ExportStream << "\t\t\t<option name=\"Auth type\"" << " type=\"string\"" << ">" <<  "cert" << "</option>" << "\n";
                    if (it->getAuthType() == VpnAccountData::psk)
                        ExportStream << "\t\t\t<option name=\"Auth type\"" << " type=\"string\"" << ">" <<  "psk" << "</option>" << "\n";
					if (it->getAuthType() == VpnAccountData::hybrid)
                        ExportStream << "\t\t\t<option name=\"Auth type\"" << " type=\"string\"" << ">" <<  "hybrid" << "</option>" << "\n";

                    ExportStream << "\t\t\t<option name=\"do ping ip\"" << " type=\"bool\"" << ">" <<  it->getDoPingIP() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Ping host IP\"" << " type=\"string\"" << ">" <<  it->getPingHostIP() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use special remote ID\"" << " type=\"bool\"" << ">" <<  it->getUseSpecialRemoteID() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use special local ID\"" << " type=\"bool\"" << ">" <<  it->getUseSpecialLocalID() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Special server certificate\"" << " type=\"string\"" << ">" <<  it->getSpecialServerCertificate() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use special server certificate\"" << " type=\"bool\"" << ">" <<  it->getUseSpecialServerCertificate() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Special remote ID\"" << " type=\"string\"" << ">" <<  it->getSpecialRemoteID() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Special local ID\"" << " type=\"string\"" << ">" <<  it->getSpecialLocalID() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Local ID type\"" << " type=\"string\"" << ">" <<  it->getLocalIDType() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Remote ID type\"" << " type=\"string\"" << ">" <<  it->getRemoteIDType() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use UDP-protocol\"" << " type=\"bool\"" << ">" <<  it->getUseUdp() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use UDP-port\"" << " type=\"bool\"" << ">" <<  it->getUseUdpPort() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"local UDP port\"" << " type=\"int\"" << ">" <<  it->getUdpPort() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"use DNS_UPDATE\"" << " type=\"bool\"" << ">" <<  it->getUseDnsUpdate() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"use DNS-server\"" << " type=\"bool\"" << ">" <<  it->getUseDnsServer() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"DNS server\"" << " type=\"string\"" << ">" <<  it->getDnsServer() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"refuse 40 bit encryption\"" << " type=\"bool\"" << ">" <<  it->getRefuse40BitEncryption() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"refuse 128 bit encryption\"" << " type=\"bool\"" << ">" <<  it->getRefuse128BitEncryption() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"require stateless encryption\"" << " type=\"bool\"" << ">" <<  it->getAllowStatefulMode() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"require mppe\"" << " type=\"bool\"" << ">" <<  it->getRequireMppe() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Disable MPPE compression\"" << " type=\"bool\"" << ">" <<  it->getDisableMPPEComp() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Local virtual IP\"" << " type=\"string\"" << ">" <<  it->getLocalVirtualIP() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Remote virtual IP\"" << " type=\"string\"" << ">" <<  it->getRemoteVirtualIP() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Pre shared key file\"" << " type=\"string\"" << ">" <<  it->getPreSharedKeyFile() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Execute command before connect\"" << " type=\"string\"" << ">" <<  it->getExecuteCmdBeforeConnect() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Execute command after connect\"" << " type=\"string\"" << ">" <<  it->getExecuteCmdAfterConnect() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Execute command before disconnect\"" << " type=\"string\"" << ">" <<  it->getExecuteCmdBeforeDisconnect() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Execute command after disconnect\"" << " type=\"string\"" << ">" <<  it->getExecuteCmdAfterDisconnect() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Command before connect\"" << " type=\"string\"" << ">" <<  it->getCommandBeforeConnect() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Command after connect\"" << " type=\"string\"" << ">" <<  it->getCommandAfterConnect() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Command before disconnect\"" << " type=\"string\"" << ">" <<  it->getCommandBeforeDisconnect() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Command after disconnect\"" << " type=\"string\"" << ">" <<  it->getCommandAfterDisconnect() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use no BSD compression\"" << " type=\"bool\"" << ">" <<  it->getUseNoBsdComp() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Do not use no IP by default\"" << " type=\"bool\"" << ">" <<  it->getUseNoIpDefault() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use no deflate\"" << " type=\"bool\"" << ">" <<  it->getUseNoDeflate() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Replace default route\"" << " type=\"bool\"" << ">" <<  it->getReplaceDefaultRoute() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use own MTU\"" << " type=\"bool\"" << ">" <<  it->getUseMtu() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use own MRU\"" << " type=\"bool\"" << ">" <<  it->getUseMru() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"MTU for pppd\"" << " type=\"int\"" << ">" <<  it->getMtu() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"MRU for pppd\"" << " type=\"int\"" << ">" <<  it->getMru() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use virtual IP\"" << " type=\"bool\"" << ">" <<  it->getUseVirtualIP() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Virtual IP\"" << " type=\"string\"" << ">" <<  it->getVirtualIP() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"PSK is in file\"" << " type=\"bool\"" << ">" <<  it->getPskIsInFile() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use additional network routes\"" << " type=\"bool\"" << ">" <<  it->getUseAdditionalNetworkRoutes() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Hash algorithm\"" << " type=\"string\"" << ">" <<  it->getHashAlgo() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Encryption algorithm\"" << " type=\"string\"" << ">" <<  it->getEncryptionAlgorithm() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Authentication algorithm\"" << " type=\"string\"" << ">" <<  it->getAuthenticationAlgorithm() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Tunnel device type\"" << " type=\"string\"" << ">" <<  it->getTunnelDeviceType() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use userdefined port\"" << " type=\"bool\"" << ">" <<  it->getUseUserdefinedPort() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Userdefined port\"" << " type=\"int\"" << ">" <<  it->getUserdefinedPort() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"NS cert type\"" << " type=\"string\"" << ">" <<  it->getNsCertType() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use NS cert type\"" << " type=\"bool\"" << ">" <<  it->getUseNsCertType() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use connection status check\"" << " type=\"bool\"" << ">" <<  it->getUseConnectionStatusCheck() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Connection check success count\"" << " type=\"int\"" << ">" <<  it->getConnectionStatusCheckSuccessCount() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Connection check status interval\"" << " type=\"int\"" << ">" <<  it->getConnectionStatusInterval() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Do reconnect after connection lost\"" << " type=\"bool\"" << ">" <<  it->getDoReconnectAfterConnectionLost() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Disable LZO compression\"" << " type=\"bool\"" << ">" <<  it->getDisableLzoCompression() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"AuthWithUsernameAndPassword\"" << " type=\"bool\"" << ">" <<  it->getAuthWithUsernameAndPassword() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"AllowEmptyGroupPassword\"" << " type=\"bool\"" << ">" <<  it->getAllowEmptyGroupPassword() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use userdefinied cipher\"" << " type=\"bool\"" << ">" <<  it->getUseUserdefiniedCipher() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Userdefinied cipher\"" << " type=\"string\"" << ">" <<  it->getUserdefiniedCipher() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use redirect gateway\"" << " type=\"bool\"" << ">" <<  it->getUseRedirectGateway() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use TLS auth\"" << " type=\"bool\"" << ">" <<  it->getUseTlsAuth() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"TLS auth file\"" << " type=\"string\"" << ">" <<  it->getTlsAuthFile() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use HTTP proxy\"" << " type=\"bool\"" << ">" <<  it->getUseHttpProxy() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"HTTP proxy host\"" << " type=\"string\"" << ">" <<  it->getHttpProxy() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"HTTP proxy port\"" << " type=\"int\"" << ">" <<  it->getHttpProxyPort() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"HTTP proxy timeout\"" << " type=\"int\"" << ">" <<  it->getHttpProxyTimeout() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Dont save username\"" << " type=\"bool\"" << ">" <<  it->getDontSaveUsername() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use mode config\"" << " type=\"bool\"" << ">" <<  it->getUseModeConfig() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Exchange mode\"" << " type=\"string\"" << ">" <<  it->getExchangeMode() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use delay at reconnect\"" << " type=\"bool\"" << ">" <<  it->getUseReconnectDelay() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Reconnect delay\"" << " type=\"int\"" << ">" <<  it->getReconnectDelay() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use TLS host\"" << " type=\"bool\"" << ">" <<  it->getUseTlsRemoteHost() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"TLS remote host\"" << " type=\"string\"" << ">" <<  it->getTlsRemoteHost() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Disable opportunistic encryption\"" << " type=\"bool\"" << ">" <<  it->getDisableOpportunisticEncryption() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Right next hop\"" << " type=\"string\"" << ">" <<  it->getRightNextHop() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Left next hop\"" << " type=\"string\"" << ">" <<  it->getLeftNextHop() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use userdefinied packet size for fragmentation\"" << " type=\"bool\"" << ">" <<  it->getUseFragment() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use userdef packet size\"" << " type=\"bool\"" << ">" <<  it->getUseMssfix() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Fragment\"" << " type=\"int\"" << ">" <<  it->getFragment() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"PeerTimeout\"" << " type=\"int\"" << ">" <<  it->getPeerTimeout() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Disable CCP\"" << " type=\"bool\"" << ">" <<  it->getDisableCcp() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use smartcard\"" << " type=\"bool\"" << ">" <<  it->getUseSmartcard() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use Xauth interactive\"" << " type=\"bool\"" << ">" <<  it->getUseXauthInteractive() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use HTTP Proxy Authentication\"" << " type=\"bool\"" << ">" <<  it->getUseHttpProxyAuth() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"HTTP Proxy Authtype\"" << " type=\"string\"" << ">" <<  it->getHttpProxyAuthType() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use HTTP Proxy Auth user\"" << " type=\"string\"" << ">" <<  it->getHttpProxyUser() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use HTTP Proxy Auth pass\"" << " type=\"string\"" << ">" <<  it->getHttpProxyPass() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use only CA cert and user auth\"" << " type=\"bool\"" << ">" <<  it->getUseOnlyCaCertAndUserAuth() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use mail address as identifier\"" << " type=\"bool\"" << ">" <<  it->getUseMailAddressAsIdentifier() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use right next hop\"" << " type=\"bool\"" << ">" <<  it->getUseRightNextHop() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use left next hop\"" << " type=\"bool\"" << ">" <<  it->getUseLeftNextHop() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Pkcs11 providers\"" << " type=\"string\"" << ">" <<  it->getPkcs11Providers() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Pkcs11 slot type\"" << " type=\"string\"" << ">" <<  it->getPkcs11SlotType() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Pkcs11 slot\"" << " type=\"string\"" << ">" <<  it->getPkcs11Slot() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Pkcs11 id type\"" << " type=\"string\"" << ">" <<  it->getPkcs11IdType() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Pkcs11 id\"" << " type=\"string\"" << ">" <<  it->getPkcs11Id() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Pkcs11 sign mode\"" << " type=\"string\"" << ">" <<  it->getPkcs11SignMode() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use Pkcs11 providers\"" << " type=\"bool\"" << ">" <<  it->getUsePkcs11Providers() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Allow empty private key password\"" << " type=\"bool\"" << ">" <<  it->getAllowEmptyPrivateKeyPassword() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Allow ip address change of peer\"" << " type=\"bool\"" << ">" <<  it->getAllowIpAddressChangeOfPeer() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Auth method\"" << " type=\"string\"" << ">" <<  it->getAuthMethod() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Command after connect delay time\"" << " type=\"string\"" << ">" <<  it->getCommandAfterConnectDelayTime() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use search domain in resolv conf\"" << " type=\"bool\"" << ">" << it->getUseSearchDomainInResolvConf() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Search domain in resolv conf\"" << " type=\"string\"" << ">" << it->getSearchDomainInResolvConf() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Authentication direction\"" << " type=\"string\"" << ">" << it->getAuthenticationDirection() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"CiscoNatMode\"" << " type=\"string\"" << ">" << it->getCiscoNatMode() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"IPSec ESP\"" << " type=\"string\"" << ">" << it->getIpsecEsp() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"IPSec IKE\"" << " type=\"string\"" << ">" << it->getIpsecIke() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Vtun profile\"" << " type=\"string\"" << ">" << it->getVtunProfile() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Disable data encryption\"" << " type=\"bool\"" << ">" << it->getDisableDataEncryption() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use authentication algorithm\"" << " type=\"bool\"" << ">" << it->getUseAuthenticationAlgorithm() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Fix path mtu discovery problem\"" << " type=\"bool\"" << ">" << it->getFixPathMtuDiscoveryProblem() <<  "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use remote network\"" << " type=\"bool\"" << ">" << int (it->getUseRemoteNetwork()) <<  "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Ipsec vpn mode\"" << " type=\"string\"" << ">" << it->getIpsecVpnMode() <<  "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"DisableHeaderCompression\"" << " type=\"bool\"" << ">" << int (it->getDisableHeaderCompression()) <<  "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"DisableMagicNumberNegotiation\"" << " type=\"bool\"" << ">" << int (it->getDisableMagicNumberNegotiation()) <<  "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"DisableIpx\"" << " type=\"bool\"" << ">" << int (it->getDisableIpx()) <<  "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Disable protocol field compression\"" << " type=\"bool\"" << ">" << int (it->getDisableProtocolFieldCompression()) <<  "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Disable address control compression\"" << " type=\"bool\"" << ">" << int (it->getDisableAddressControlCompression()) <<  "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use custom ike\"" << " type=\"bool\"" << ">" << int (it->getUseCustomIke()) <<  "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use custom esp\"" << " type=\"bool\"" << ">" << int (it->getUseCustomEsp()) <<  "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Verify ca cert\"" << " type=\"bool\"" << ">" << int (it->getVerifyCaCert()) <<  "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use DPD idle timeout\"" << " type=\"bool\"" << ">" << int (it->getUseDpdIdleTimeout()) <<  "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"DPD idle timeout\"" << " type=\"int\"" << ">" <<  it->getDpdIdleTimeout() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Hide group password in accountdata dialog\"" << " type=\"bool\"" << ">" << int (it->getHideGroupPasswordInAccountDataDialog()) <<  "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"MaxConnectTries\"" << " type=\"int\"" << ">" <<  it->getMaxConnectTries() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"L2tpDaemon\"" << " type=\"int\"" << ">" <<  it->getL2tpDaemon() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"UseLeftSourceIp\"" << " type=\"bool\"" << ">" << int (it->getUseLeftSourceIp()) << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"UseRightSourceIp\"" << " type=\"bool\"" << ">" << int (it->getUseRightSourceIp()) << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"LeftSourceIp\"" << " type=\"string\"" << ">" << it->getLeftSourceIp() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"RightSourceIp\"" << " type=\"string\"" << ">" << it->getRightSourceIp() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Use virtual subnets\"" << " type=\"bool\"" << ">" << int (it->getUseVirtualSubnetworks()) << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"Virtual subnets\"" << " type=\"string\"" << ">" << it->getVirtualSubnetworks() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"DisablePushFromServer\"" << " type=\"bool\"" << ">" << int (it->getDisablePushFromServer()) << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"DisableBind\"" << " type=\"bool\"" << ">" << int (it->getDisableBind()) << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"UseRenegSec\"" << " type=\"bool\"" << ">" << int (it->getUseRenegSec()) << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"RenegSec\"" << " type=\"int\"" << ">" << it->getRenegSec() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"UseTunnelPing\"" << " type=\"bool\"" << ">" << int (it->getUseTunnelPing())  << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"TunnelPing\"" << " type=\"int\"" << ">" << it->getTunnelPing() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"UseTunnelPingRestart\"" << " type=\"bool\"" << ">" << int (it->getUseTunnelPingRestart()) << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"TunnelPingRestart\"" << " type=\"int\"" << ">" <<  it->getTunnelPingRestart() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"RequireEap\"" << " type=\"bool\"" << ">" << int (it->getRequireEap()) << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"UseSshConfigRemoteScript\"" << " type=\"bool\"" << ">" << int (it->getUseSshConfigRemoteScript()) << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"SshConfigRemoteScript\"" << " type=\"string\"" << ">" << it->getSshConfigRemoteScript() << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"AskUserPasswordOnEachConnect\"" << " type=\"bool\"" << ">" << int(it->getAskUserPasswordOnEachConnect()) << "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"UseCiscoCertStore\"" << " type=\"bool\"" << ">" <<int( it->getUseCiscoCertStore())<< "</option>" << "\n";
                    ExportStream << "\t\t\t<option name=\"UseNat\"" << " type=\"bool\"" << ">" <<int( it->getUseNat())<< "</option>" << "\n";

                    ExportStream << "\t\t</profile>" << "\n";
                    exportCount++;
                }

            }
            ExportStream << "\t</profiles>" << "\n";
            ExportStream << "</kvpnc>" << "\n";
            exportfile.close();
        } else {
            KMessageBox::error(0, i18n("Failed to create \"%1\"." ,   filename));
            return false;
        }
    } else {
        KMessageBox::information(0, i18n("Export canceled."));
        return false;
    }
    QString msg = "";
    if (exportCount > 0 && exportGlobal == true)
        msg = i18np("Export was successful. %1 profile and global settings were exported.", "Export was successful. %1 profiles and global settings were exported.", exportCount);
    if (exportCount > 0 && exportGlobal == false)
        msg = i18np("Export was successful. %1 profile were exported.", "Export was successful. %1 profiles were exported.", exportCount);
    if (exportCount < 1 && exportGlobal == true)
        msg = i18n("Export was successful. Global settings were exported.");
    KMessageBox::information(0, msg, i18n("Export success"));
    return true;
}

bool KVpncConfig::importKvpncConfig(QString filename, QString& RetName, bool& openProfileManager)
{
    QFile importfile(filename);
    if (!importfile.exists()) {
        KMessageBox::error(0, i18n("Failed to read \"%1\"." ,   filename));
        return false;
    }
    QString kvpncexportversion = "";

    QString pathToVpnc;
    QString pathToCiscoVpnc;
    QString pathToRacoon;
    QString pathToRacoonctl;
    QString pathToSetkey;
    QString pathToIptables;
    QString pathToOpenssl;
    QString pathToIpsec;
    QString pathToPppd;
    QString pathToPptp;
    QString pathToL2tpd;
    QString pathToXl2tpd;
    QString pathToOpenl2tp;
    QString pathToKill;
    QString pathToKillall;
    QString pathToPing;
    QString pathToOpenvpn;
    QString pathToIp;
    QString pathToIfconfig;
    QString pathToRoute;
    QString pathToNetstat;
    QString pathToPkcs11Tool;
    QString pathToVtund;
    QString pathToCiscoCertMgr;
    QString pathToTail;
    QString pathToSsh;
    QString pathToKsshAskpass;
    QString pathToGnomeSshAskpass;
    QString AutoConnectProfile;
    QString RacoonDebugLevel;
    QString Vpnc_pid_file;
    QString Pppd_pid_file;
    QString lastProfile;
    QString logfileName;

    QString TmpPassword; //< from enter password dialog
    QString TmpGroupPassword; //< from enter password dialog
    QString TmpUsername; //< from enter password dialog
    QString TmpPrivKeyPassStr;
    QString TmpGatewayIP;
    QString TmpXauthInterPasscode; //< from Xauth interactive passcode dialog
    QString TmpPrivateKeyPass;
    QString TmpHttpProxyPassword;

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

    int VpncDebugLevel = 0;
    int KvpncDebugLevel = 1;
    int OpenvpnDebugLevel = 0;
    int PptpLogLevel = 0;
    int SshDebugLevel = 0;
    int PppdKernelLogLevel = 0;
    int LogViewerFontSize = 10;
    int mainwindow_pos_x = 10;
    int mainwindow_pos_y = 10;
    int mainwindow_height = 600;
    int mainwindow_width = 800;
    int connectSleepDelay = 10;
    int connectSleepRetry = 3;
    int tryConnectTimeout = 30;
    int connectionStartTime = 0;
    int runningCheckCounter = 0;
    int runningCheckTimeout = 0;
    int OpenvpnManagementPort = 2222;
    QList<VpnAccountData*> *ImportedAccountList;

    QColor InfoLogColor;
    QColor RemoteLogColor;
    QColor ErrorLogColor;
    QColor SuccessLogColor;
    QColor DebugLogColor;
    QColor DebugBackgroundcolor;

    QPoint pos;
    QPoint WindowPos;
    QSize WindowSize;

    bool importGlobal = false;
    int importCount = 0;

    QDomDocument doc("kvpncsettingsdoc");
    if (importfile.open(QIODevice::ReadOnly)) {
        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

        if (!doc.setContent(&importfile)) {
            importfile.close();
            KMessageBox::error(0, i18n("Failed to read \"%1\"." , filename));
            appendLogEntry(i18n("Failed to read \"%1\"." , filename), KVpncEnum::error);
            QApplication::restoreOverrideCursor();

            return false;
        }
        importfile.close();

        // print out the element names of all elements that are direct children
        // of the outermost element.
        QDomElement docElem = doc.documentElement();

        QDomNode n = docElem.firstChild();
        while (!n.isNull()) {
            if (n.toElement().tagName()  == "version") {
                QDomNodeList vsubnodes = n.toElement().childNodes();
                for (int i = 0;i <= (int) vsubnodes.count();i++) {
                    QDomNode n1 = vsubnodes.item(i);
                    if (n1.toElement().tagName() == "app") {
                    }
                    if (n1.toElement().tagName() == "exportversion") {
                        kvpncexportversion = n1.toElement().text();
                    }
                }
            }

            if (n.toElement().tagName()  == "global") {
                QDomNodeList vsubnodes = n.toElement().childNodes();
                for (int i = 0;i <= (int) vsubnodes.count();i++) {
                    QDomNode n1 = vsubnodes.item(i);
                    if (n1.toElement().tagName() != "") {
                    }
                    if (n1.toElement().tagName() == "Minimize after connect") {
                        minimizeAfterConnect = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Hide on startup") {
                        hideMainWindow = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Use silent quit") {
                        useSilentQuit = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Dont quit on CloseEvent") {
                        dontQuitOnCloseEvent = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Enable pppd debug") {
                        enableDebugPppd = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Enable pptpd debug") {
                        enableDebugPptpd = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Enable l2tpd debug") {
                        enableDebugL2tpd = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Enable xl2tpd debug") {
                        enableDebugXl2tpd = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Enable openl2tp debug") {
                        enableDebugOpenl2tp = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Enable FreeSWAN verbose") {
                        enableFreeswanVerbose = n1.toElement().text().toInt();
                    } else if ( n1.toElement().tagName() == "Pluto Debug" ) {
                        PlutoDebug = QStringList::split(' ', n1.toElement().text());
                    } else if ( n1.toElement().tagName() == "Klips Debug" ) {
                        KlipsDebug = QStringList::split(' ', n1.toElement().text());
                    } else if (n1.toElement().tagName() == "Show debugconsole") {
                        showDebugConsole = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Pid file for vpnc ") {
                        Vpnc_pid_file = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Vpnc debuglevel") {
                        VpncDebugLevel = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Racoon debuglevel") {
                        RacoonDebugLevel = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Kvpnc debuglevel") {
                        KvpncDebugLevel = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Pppd debuglevel") {
                        PppdDebugLevel = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Pppd kernel log level") {
                        PppdKernelLogLevel = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Openvpn debuglevel") {
                        OpenvpnDebugLevel = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Pptp debuglevel") {
                        PptpLogLevel = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Ssh debuglevel") {
                        SshDebugLevel = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Path to vpnc-bin") {
                        pathToVpnc = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to vpnclient") {
                        pathToCiscoVpnc = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to racoon") {
                        pathToRacoon = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to racoonctl") {
                        pathToRacoonctl = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to setkey") {
                        pathToSetkey = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to iptables") {
                        pathToIptables = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to openssl") {
                        pathToOpenssl = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to freeswan") {
                        pathToIpsec = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to pppd") {
                        pathToPppd = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to pptp") {
                        pathToPptp = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to l2tpd") {
                        pathToL2tpd = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to xl2tpd") {
                        pathToXl2tpd = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to openl2tp") {
                        pathToOpenl2tp = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to kill") {
                        pathToKill = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to kill-all") {
                        pathToKillall = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to ping") {
                        pathToPing = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to openvpn") {
                        pathToOpenvpn = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to iputility") {
                        pathToIp = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to ifconfig") {
                        pathToIfconfig = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to route") {
                        pathToRoute = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to netstat") {
                        pathToNetstat = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to pkcs11-tool") {
                        pathToPkcs11Tool = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to vtund") {
                        pathToVtund = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to cisco_cert_mgr") {
                        pathToCiscoCertMgr = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to tail") {
                        pathToTail = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to ssh") {
                        pathToSsh = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to ksshaskpass") {
                        pathToKsshAskpass = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Path to ssh-askpass-gnome") {
                        pathToGnomeSshAskpass = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Show Statusbar") {
                        showStatusBar = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Try connect timeout") {
                        tryConnectTimeout = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Last Profile") {
                        lastProfile = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Write log file") {
                        writeLogFile = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Hold generated scripts") {
                        holdGeneratedScripts = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Programs in path") {
                        programsInPath = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Info logwindow color") {
                        InfoLogColor.name()  = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Remote logwindow color") {
                        RemoteLogColor.name()  = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Error logwindow color") {
                        ErrorLogColor.name()  = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Success  logwindow color") {
                        SuccessLogColor.name()  = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Debug logwindow color") {
                        DebugLogColor.name()  = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Debug background color") {
                        DebugBackgroundcolor.name()  = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Use colorized log output") {
                        useColorizedLogOutput = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Show interface IP in tooltip") {
                        showInterfaceIPinTooltip = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Auto connect profile") {
                        AutoConnectProfile = n1.toElement().text();
                    } else if (n1.toElement().tagName() == "Do auto connect at startup") {
                        doAutoConnectAtStartup = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Log viewer font size") {
                        LogViewerFontSize = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Mainwindow width") {
                        mainwindow_width = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Mainwindow height") {
                        mainwindow_height = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Mainwindow position x") {
                        mainwindow_pos_x = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Mainwindow position y") {
                        mainwindow_pos_y = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Openvpn management port") {
                        OpenvpnManagementPort = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "hideOnCloseInfo") {
                        hideOnCloseInfo = n1.toElement().text().toInt();
                    }
                    //   else if (n1.toElement().tagName() == "ToolBar Settings") { parent->toolBar( "mainToolBar" ) = n1.toElement().text(); }
                    else if (n1.toElement().tagName() == "Use KWallet") {
                        useKwallet = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "FeedbackMailSent") {
                        feedbackMailSent = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Do kill l2tpd if still running") {
                        doKillL2tpdIfStillRunning = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Do kill xl2tpd if still running") {
                        doKillXl2tpdIfStillRunning = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Do kill racoon if still running") {
                        doKillRacoonIfStillRunning = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Show connection time in Tooltip") {
                        showConnectionTimeInTooltip = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "Enable debug Openvpn") {
                        enableDebugOpenvpn = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "EnableDebugXl2tpdNetwork") {
                        enableDebugXl2tpdNetwork  = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "EnableDebugXl2tpdpacket") {
                        enableDebugXl2tpdpacket = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "EnableDebugXl2tpdstate") {
                        enableDebugXl2tpdstate = n1.toElement().text().toInt();
                    } else if (n1.toElement().tagName() == "EnableDebugXl2tpdtunnel") {
                        enableDebugXl2tpdtunnel = n1.toElement().text().toInt();
                    }
                }
            }

            if (n.toElement().tagName()  == "profiles") {
                ImportedAccountList = new QList<VpnAccountData*>();
                QDomNodeList profiles_subnodes = n.toElement().childNodes();
                for (int i = 0;i <= (int) profiles_subnodes.count();i++) {
                    QDomNode n1 = profiles_subnodes.item(i);
                    if (n1.toElement().attribute("name") != "") {
                        QString name = n1.toElement().attribute("name");
                        VpnAccountData *data = new VpnAccountData(VpnAccountData::cisco, name);    // cisco is a dummy here, it will be set later
                        data->setDescription(i18n("import from ") + filename);

                        QDomNodeList profile_subnodes = n1.toElement().childNodes();
                        for (int j = 0;j <= (int) profile_subnodes.count();j++) {
                            QDomNode n2 = profile_subnodes.item(j);
                            if (n2.toElement().attribute("name") != "") {
                                QString elementname = n2.toElement().attribute("name");
                                QString elementvalue = n2.toElement().text();
                                // normal config
                                if (elementname == "Connection type") {
                                    QString type = elementvalue;
                                    VpnAccountData::ConnectionType ConnType = VpnAccountData::ConnectionType(VpnAccountData::cisco);
                                    if (type == "cisco")
                                        ConnType = VpnAccountData::cisco;
                                    else if (type == "ciscoorig")
                                        ConnType = VpnAccountData::ciscoorig;
                                    else if (type == "racoon")
                                        ConnType = VpnAccountData::racoon;
                                    else if (type == "l2tpd (racoon)")
                                        ConnType = VpnAccountData::l2tpd_racoon;
                                    else if (type == "freeswan")
                                        ConnType = VpnAccountData::freeswan;
                                    else if (type == "l2tpd (openswan)")
                                        ConnType = VpnAccountData::l2tpd_freeswan;
                                    else if (type == "pptp")
                                        ConnType = VpnAccountData::pptp;
                                    else if (type == "openvpn")
                                        ConnType = VpnAccountData::openvpn;
                                    else if (type == "vtun")
                                        ConnType = VpnAccountData::vtun;
                                    else if (type == "ssh")
                                        ConnType = VpnAccountData::ssh;
                                    else
                                        ConnType = VpnAccountData::other;
                                    data->setConnectionType(ConnType);
                                }

                                else if (elementname == "VPN Gateway") {
                                    data->setGateway(elementvalue);
                                } else if (elementname == "VPN ID") {
                                    data->setID(elementvalue);
                                } else if (elementname == "Username") {
                                    data->setUserName(elementvalue);
                                }

                                else if (elementname == "Save user password") {
                                    data->setSaveUserPassword(elementvalue.toInt());
                                } else if (elementname == "Save PSK") {
                                    data->setSavePsk(elementvalue.toInt());
                                } else if (elementname == "Save private key password") {
                                    data->setSavePrivateKeyPassword(elementvalue.toInt());
                                } else if (elementname == "Private key") {
                                    data->setPrivateKey(elementvalue);
                                } else if (elementname == "Use advanced settings") {
                                    data->setUseAdvancedSettings(elementvalue.toInt());
                                } else if (elementname == "Application version") {
                                    data->setApplicationVersion(elementvalue);
                                } else if (elementname == "Local port") {
                                    data->setLocalPort(elementvalue.toInt());
                                } else if (elementname == "Remote port") {
                                    data->setRemotePort(elementvalue.toInt());
                                } else if (elementname == "NT domain name") {
                                    data->setNtDomainName(elementvalue);
                                } else if (elementname == "Perfect forward secrety") {
                                    data->setPerfectForwardSecrety(elementvalue);
                                } else if (elementname == "IKE group") {
                                    data->setIkeGroup(elementvalue);
                                }

                                else if (elementname == "Use application version") {
                                    data->setUseApplicationVersion(elementvalue.toInt());
                                } else if (elementname == "Use global IPSec secret") {
                                    data->setUseGlobalIpsecSecret(elementvalue.toInt());
                                } else if (elementname == "Use IKE group") {
                                    data->setUseIkeGroup(elementvalue.toInt());
                                } else if (elementname == "Use local port") {
                                    data->setUseLocalPort(elementvalue.toInt());
                                } else if (elementname == "Use remote port") {
                                    data->setUseRemotePort(elementvalue.toInt());
                                } else if (elementname == "Use NT domain name") {
                                    data->setUseNtDomainName(elementvalue.toInt());
                                } else if (elementname == "Use single DES") {
                                    data->setUseSingleDes(elementvalue.toInt());
                                } else if (elementname == "Use perfect Forward Secrety") {
                                    data->setUsePerfectForwardSecrety(elementvalue.toInt());
                                } else if (elementname == "Remote net address") {
                                    data->setRemoteNetAddr(elementvalue);
                                } else if (elementname == "Remote net mask") {
                                    data->setRemoteNetMask(elementvalue);
                                }

                                else if (elementname == "x509 certificate") {
                                    data->setX509Certificate(elementvalue);
                                } else if (elementname == "Ca certificate") {
                                    data->setCaCertificate(elementvalue);
                                } else if (elementname == "Network device") {
                                    data->setNetworkDevice(elementvalue);
                                } else if (elementname == "Cert path") {
                                    data->setCertPath(elementvalue);
                                }

                                else if (elementname == "Auth type") {
                                    QString Authtype = elementvalue;
                                    if (Authtype == "cert")
                                        data->setAuthType(VpnAccountData::cert);
                                    else if (Authtype == "psk")
                                        data->setAuthType(VpnAccountData::psk);
                                    else if (Authtype == "hybrid")
                                        data->setAuthType(VpnAccountData::hybrid);
                                    else
                                        data->setAuthType(VpnAccountData::unknownauth);

                                    if ((data->getConnectionType() == VpnAccountData::pptp || data->getConnectionType() == VpnAccountData::openvpn) && (Authtype != "cert" && Authtype == "psk"))
                                        data->setAuthType(VpnAccountData::cert);

                                } else if (elementname == "do ping ip") {
                                    data->setDoPingIP(elementvalue.toInt());
                                } else if (elementname == "Ping host IP") {
                                    data->setPingHostIP(elementvalue);
                                }

                                else if (elementname == "Special server certificate") {
                                    data->setSpecialServerCertificate(elementvalue);
                                } else if (elementname == "Use special server certificate") {
                                    data->setUseSpecialServerCertificate(elementvalue.toInt());
                                } else if (elementname == "Special remote ID") {
                                    data->setSpecialRemoteID(elementvalue);
                                } else if (elementname == "Special local ID") {
                                    data->setSpecialLocalID(elementvalue);
                                } else if (elementname == "Local ID type") {
                                    data->setLocalIDType(elementvalue);
                                } else if (elementname == "Remote ID type") {
                                    data->setRemoteIDType(elementvalue);
                                } else if (elementname == "Use UDP-protocol") {
                                    data->setUseUdp(elementvalue.toInt());
                                } else if (elementname == "Use UDP-port") {
                                    data->setUseUdpPort(elementvalue.toInt());
                                } else if (elementname == "local UDP port") {
                                    data->setUdpPort(elementvalue.toInt());
                                } else if (elementname == "use DNS_UPDATE") {
                                    data->setUseDnsUpdate(elementvalue.toInt());
                                } else if (elementname == "use DNS-server") {
                                    data->setUseDnsServer(elementvalue.toInt());
                                } else if (elementname == "DNS server") {
                                    data->setDnsServer(elementvalue);
                                } else if (elementname == "refuse 40 bit encryption") {
                                    data->setRefuse40BitEncryption(elementvalue.toInt());
                                } else if (elementname == "refuse 128 bit encryption") {
                                    data->setRefuse128BitEncryption(elementvalue.toInt());
                                } else if (elementname == "require stateless encryption") {
                                    data->setAllowStatefulMode(elementvalue.toInt());
                                } else if (elementname == "require mppe") {
                                    data->setRequireMppe(elementvalue.toInt());
                                } else if (elementname == "Disable MPPE compression") {
                                    data->setDisableMPPEComp(elementvalue.toInt());
                                } else if (elementname == "Local virtual IP") {
                                    data->setLocalVirtualIP(elementvalue);
                                } else if (elementname == "Remote virtual IP") {
                                    data->setRemoteVirtualIP(elementvalue);
                                } else if (elementname == "Pre shared key file") {
                                    data->setPreSharedKeyFile(elementvalue);
                                } else if (elementname == "Execute command before connect") {
                                    data->setExecuteCmdBeforeConnect(elementvalue.toInt());
                                } else if (elementname == "Execute command after connect") {
                                    data->setExecuteCmdAfterConnect(elementvalue.toInt());
                                } else if (elementname == "Execute command before disconnect") {
                                    data->setExecuteCmdBeforeDisconnect(elementvalue.toInt());
                                } else if (elementname == "Execute command after disconnect") {
                                    data->setExecuteCmdAfterDisconnect(elementvalue.toInt());
                                } else if (elementname == "Command before connect") {
                                    data->setCommandBeforeConnect(elementvalue);
                                } else if (elementname == "Command after connect") {
                                    data->setCommandAfterConnect(elementvalue);
                                } else if (elementname == "Command before disconnect") {
                                    data->setCommandBeforeDisconnect(elementvalue);
                                } else if (elementname == "Command after disconnect") {
                                    data->setCommandAfterDisconnect(elementvalue);
                                } else if (elementname == "Use no BSD compression") {
                                    data->setUseNoBsdComp(elementvalue.toInt());
                                } else if (elementname == "Do not use no IP by default") {
                                    data->setUseNoIpDefault(elementvalue.toInt());
                                } else if (elementname == "Use no deflate") {
                                    data->setUseNoDeflate(elementvalue.toInt());
                                } else if (elementname == "Replace default route") {
                                    data->setReplaceDefaultRoute(elementvalue.toInt());
                                } else if (elementname == "Use own MTU") {
                                    data->setUseMtu(elementvalue.toInt());
                                } else if (elementname == "Use own MRU") {
                                    data->setUseMru(elementvalue.toInt());
                                } else if (elementname == "MTU for pppd") {
                                    data->setMtu(elementvalue.toInt());
                                } else if (elementname == "MRU for pppd") {
                                    data->setMru(elementvalue.toInt());
                                } else if (elementname == "Use virtual IP") {
                                    data->setUseVirtualIP(elementvalue.toInt());
                                } else if (elementname == "Virtual IP") {
                                    data->setVirtualIP(elementvalue);
                                } else if (elementname == "PSK is in file") {
                                    data->setPskIsInFile(elementvalue.toInt());
                                } else if (elementname == "Use additional network routes") {
                                    data->setUseAdditionalNetworkRoutes(elementvalue.toInt());
                                } else if (elementname == "Hash algorithm") {
                                    data->setHashAlgo(elementvalue);
                                } else if (elementname == "Encryption algorithm") {
                                    data->setEncryptionAlgorithm(elementvalue);
                                } else if (elementname == "Authentication algorithm") {
                                    data->setAuthenticationAlgorithm(elementvalue);
                                } else if (elementname == "Tunnel device type") {
                                    data->setTunnelDeviceType(elementvalue);
                                } else if (elementname == "Use userdefined port") {
                                    data->setUseUserdefinedPort(elementvalue.toInt());
                                } else if (elementname == "Userdefined port") {
                                    data->setUserdefinedPort(elementvalue.toInt());
                                } else if (elementname == "NS cert type") {
                                    data->setNsCertType(elementvalue);
                                } else if (elementname == "Use NS cert type") {
                                    data->setUseNsCertType(elementvalue.toInt());
                                } else if (elementname == "Use connection status check") {
                                    data->setUseConnectionStatusCheck(elementvalue.toInt());
                                } else if (elementname == "Connection check success count") {
                                    data->setConnectionStatusCheckSuccessCount(elementvalue.toInt());
                                } else if (elementname == "Connection check status interval") {
                                    data->setConnectionStatusInterval(elementvalue.toInt());
                                } else if (elementname == "Do reconnect after connection lost") {
                                    data->setDoReconnectAfterConnectionLost(elementvalue.toInt());
                                } else if (elementname == "Disable LZO compression") {
                                    data->setDisableLzoCompression(elementvalue.toInt());
                                } else if (elementname == "AuthWithUsernameAndPassword") {
                                    data->setAuthWithUsernameAndPassword(elementvalue.toInt());
                                } else if (elementname == "AllowEmptyGroupPassword") {
                                    data->setAllowEmptyGroupPassword(elementvalue.toInt());
                                } else if (elementname == "Use userdefinied cipher") {
                                    data->setUseUserdefiniedCipher(elementvalue.toInt());
                                } else if (elementname == "Userdefinied cipher") {
                                    data->setUserdefiniedCipher(elementvalue);
                                } else if (elementname == "Use redirect gateway") {
                                    data->setUseRedirectGateway(elementvalue.toInt());
                                }
                                //     appPointer->processEvents(<< "</option>") { "\n";
                                else if (elementname == "Use TLS auth") {
                                    data->setUseTlsAuth(elementvalue.toInt());
                                } else if (elementname == "TLS auth file") {
                                    data->setTlsAuthFile(elementvalue);
                                } else if (elementname == "Use HTTP proxy") {
                                    data->setUseHttpProxy(elementvalue.toInt());
                                } else if (elementname == "HTTP proxy host") {
                                    data->setHttpProxy(elementvalue);
                                } else if (elementname == "HTTP proxy port") {
                                    data->setHttpProxyPort(elementvalue.toInt());
                                } else if (elementname == "HTTP proxy timeout") {
                                    data->setHttpProxyTimeout(elementvalue.toInt());
                                } else if (elementname == "Dont save username") {
                                    data->setDontSaveUsername(elementvalue.toInt());
                                } else if (elementname == "Use mode config") {
                                    data->setUseModeConfig(elementvalue.toInt());
                                } else if (elementname == "Exchange mode") {
                                    data->setExchangeMode(elementvalue);
                                } else if (elementname == "Use delay at reconnect") {
                                    data->setUseReconnectDelay(elementvalue.toInt());
                                } else if (elementname == "Reconnect delay") {
                                    data->setReconnectDelay(elementvalue.toInt());
                                } else if (elementname == "Use TLS host") {
                                    data->setUseTlsRemoteHost(elementvalue.toInt());
                                } else if (elementname == "TLS remote host") {
                                    data->setTlsRemoteHost(elementvalue);
                                } else if (elementname == "Disable opportunistic encryption") {
                                    data->setDisableOpportunisticEncryption(elementvalue.toInt());
                                } else if (elementname == "Right next hop") {
                                    data->setRightNextHop(elementvalue);
                                } else if (elementname == "Left next hop") {
                                    data->setLeftNextHop(elementvalue);
                                } else if (elementname == "Use userdefinied packet size for fragmentation") {
                                    data->setUseFragment(elementvalue.toInt());
                                } else if (elementname == "Use userdef packet size") {
                                    data->setUseMssfix(elementvalue.toInt());
                                } else if (elementname == "Fragment") {
                                    data->setFragment(elementvalue.toInt());
                                } else if (elementname == "PeerTimeout") {
                                    data->setPeerTimeout(elementvalue.toInt());
                                } else if (elementname == "Disable CCP") {
                                    data->setDisableCcp(elementvalue.toInt());
                                } else if (elementname == "Use smartcard") {
                                    data->setUseSmartcard(elementvalue.toInt());
                                } else if (elementname == "Use Xauth interactive") {
                                    data->setUseXauthInteractive(elementvalue.toInt());
                                } else if (elementname == "Use HTTP Proxy Authentication") {
                                    data->setUseHttpProxyAuth(elementvalue.toInt());
                                } else if (elementname == "HTTP Proxy Authtype") {
                                    data->setHttpProxyAuthType(elementvalue);
                                } else if (elementname == "HTTP Proxy Auth user") {
                                    data->setHttpProxyUser(elementvalue);
                                } else if (elementname == "HTTP Proxy Auth pass") {
                                    data->setHttpProxyPass(elementvalue);
                                } else if (elementname == "Use only CA cert and user auth") {
                                    data->setUseOnlyCaCertAndUserAuth(elementvalue.toInt());
                                } else if (elementname == "Use mail address as identifier") {
                                    data->setUseMailAddressAsIdentifier(elementvalue.toInt());
                                } else if (elementname == "Use right next hop") {
                                    data->setUseRightNextHop(elementvalue.toInt());
                                } else if (elementname == "Use left next hop") {
                                    data->setUseLeftNextHop(elementvalue.toInt());
                                } else if (elementname == "Pkcs11 providers") {
                                    data->setPkcs11Providers(elementvalue);
                                } else if (elementname == "Pkcs11 slot type") {
                                    data->setPkcs11SlotType(elementvalue);
                                } else if (elementname == "Pkcs11 slot") {
                                    data->setPkcs11Slot(elementvalue);
                                } else if (elementname == "Pkcs11 id type") {
                                    data->setPkcs11IdType(elementvalue);
                                } else if (elementname == "Pkcs11 id") {
                                    data->setPkcs11Id(elementvalue);
                                } else if (elementname == "Pkcs11 sign mode") {
                                    data->setPkcs11SignMode(elementvalue);
                                } else if (elementname == "Use Pkcs11 providers") {
                                    data->setUsePkcs11Providers(elementvalue.toInt());
                                } else if (elementname == "Allow empty private key password") {
                                    data->setAllowEmptyPrivateKeyPassword(elementvalue.toInt());
                                } else if (elementname == "Allow ip address change of peer") {
                                    data->setAllowIpAddressChangeOfPeer(elementvalue.toInt());
                                } else if (elementname == "Auth method") {
                                    data->setAuthMethod(elementvalue);
                                } else if (elementname == "Command after connect delay time") {
                                    data->setCommandAfterConnectDelayTime(elementvalue.toInt());
                                } else if (elementname == "Use search domain in resolv conf") {
                                    data->setUseSearchDomainInResolvConf(elementvalue.toInt());
                                } else if (elementname == "Search domain in resolv conf") {
                                    data->setSearchDomainInResolvConf(elementvalue);
                                } else if (elementname == "Authentication direction") {
                                    data->setAuthenticationDirection(elementvalue);
                                } else if (elementname == "CiscoNatMode") {
                                    data->setCiscoNatMode(elementvalue);
                                } else if (elementname == "IPSec ESP") {
                                    data->setIpsecEsp(elementvalue);
                                } else if (elementname == "IPSec IKE") {
                                    data->setIpsecIke(elementvalue);
                                } else if (elementname == "Vtun profile") {
                                    data->setVtunProfile(elementvalue);
                                } else if (elementname == "Disable data encryption") {
                                    data->setDisableDataEncryption(elementvalue.toInt());
                                } else if (elementname == "Use authentication algorithm") {
                                    data->setUseAuthenticationAlgorithm(elementvalue.toInt());
                                } else if (elementname == "Fix path mtu discovery problem") {
                                    data->setFixPathMtuDiscoveryProblem(elementvalue.toInt());
                                } else if (elementname == "Use remote network") {
                                    data->setUseRemoteNetwork(elementvalue.toInt());
                                } else if (elementname == "Ipsec vpn mode") {
                                    data->setIpsecVpnMode(elementvalue);
                                } else if (elementname == "DisableHeaderCompression") {
                                    data->setDisableHeaderCompression(elementvalue.toInt());
                                } else if (elementname == "DisableMagicNumberNegotiation") {
                                    data->setDisableMagicNumberNegotiation(elementvalue.toInt());
                                } else if (elementname == "DisableIpx") {
                                    data->setDisableIpx(elementvalue.toInt());
                                } else if (elementname == "Disable protocol field compression") {
                                    data->setDisableProtocolFieldCompression(elementvalue.toInt());
                                } else if (elementname == "Disable address control compression") {
                                    data->setDisableAddressControlCompression(elementvalue.toInt());
                                } else if (elementname == "Use custom ike") {
                                    data->setUseCustomIke(elementvalue.toInt());
                                } else if (elementname == "Use custom esp") {
                                    data->setUseCustomEsp(elementvalue.toInt());
                                } else if (elementname == "Verify ca cert") {
                                    data->setVerifyCaCert(elementvalue.toInt());
                                } else if (elementname == "Use DPD idle timeout") {
                                    data->setUseDpdIdleTimeout(elementvalue.toInt());
                                } else if (elementname == "DPD idle timeout") {
                                    data->setDpdIdleTimeout(elementvalue.toInt());
                                } else if (elementname == "Hide group password in accountdata dialog") {
                                    data->setHideGroupPasswordInAccountDataDialog(elementvalue.toInt());
                                } else if (elementname == "MaxConnectTries") {
                                    data->setMaxConnectTries(elementvalue.toInt());
                                } else if (elementname == "L2tpDaemon") {
                                    data->setL2tpDaemon((VpnAccountData::L2tpDaemonType) elementvalue.toInt());
                                } else if (elementname == "UseLeftSourceIp") {
                                    data->setUseLeftSourceIp(elementvalue.toInt());
                                } else if (elementname == "UseRightSourceIp") {
                                    data->setUseRightSourceIp(elementvalue.toInt());
                                } else if (elementname == "LeftSourceIp") {
                                    data->setLeftSourceIp(elementvalue);
                                } else if (elementname == "RightSourceIp") {
                                    data->setRightSourceIp(elementvalue);
                                } else if (elementname == "Use virtual subnets") {
                                    data->setUseVirtualSubnetworks(elementvalue.toInt());
                                } else if (elementname == "Virtual subnets") {
                                    data->setVirtualSubnetworks(elementvalue);
                                } else if (elementname == "DisablePushFromServer") {
                                    data->setDisablePushFromServer(elementvalue.toInt());
                                } else if (elementname == "DisableBind") {
                                    data->setDisableBind(elementvalue.toInt());
                                } else if (elementname == "UseRenegSec") {
                                    data->setUseRenegSec(elementvalue.toInt());
                                } else if (elementname == "RenegSec") {
                                    data->setRenegSec(elementvalue.toInt());
                                } else if (elementname == "UseTunnelPing") {
                                    data->setUseTunnelPing(elementvalue.toInt());
                                } else if (elementname == "TunnelPing") {
                                    data->setTunnelPing(elementvalue.toInt());
                                } else if (elementname == "UseTunnelPingRestart") {
                                    data->setUseTunnelPingRestart(elementvalue.toInt());
                                } else if (elementname == "TunnelPingRestart") {
                                    data->setTunnelPingRestart(elementvalue.toInt());
                                } else if (elementname == "RequireEap") {
                                    data->setRequireEap(elementvalue.toInt());
                                } else if (elementname == "UseSshConfigRemoteScript") {
                                    data->setUseSshConfigRemoteScript(elementvalue.toInt());
                                } else if (elementname == "SshConfigRemoteScript") {
                                    data->setSshConfigRemoteScript(elementvalue);
                                } else if (elementname == "AskUserPasswordOnEachConnect") {
                                    data->setAskUserPasswordOnEachConnect(elementvalue.toInt());
                                } else if (elementname == "UseCiscoCertStore") {
                                    data->setUseCiscoCertStore(elementvalue.toInt());
                                } else if (elementname == "UseNat") {
                                    data->setUseNat(elementvalue.toInt());
                                }

                            }
                        }
                        ImportedAccountList->append(data);
                    }
                    appPointer->processEvents();
                }
                QApplication::restoreOverrideCursor();
                KvpncImportProfileSelectionDialog selectdlg(0);
                selectdlg.setButtonText(KDialog::Apply, i18n("&Import selected profiles..."));
                VpnAccountData *it = NULL;
                QList<QTreeWidgetItem *> items;
                QStringList values;
                if (!ImportedAccountList->isEmpty()) {
                    selectdlg.ImportProfileListView->setColumnCount(3);
                    QStringList LabelList;
                    LabelList << i18n("Name") << i18n("Type") << i18n("Gateway");
                    selectdlg.ImportProfileListView->setHeaderLabels(LabelList);

                    for (int accountIdx = 0; accountIdx < ImportedAccountList->size(); ++accountIdx) {
                        it = ImportedAccountList->at(accountIdx);
                        QString name = it->getName();
                        QString type;
                        if (it->getConnectionType() == VpnAccountData::cisco)
                            type = "cisco" ;
                        else if (it->getConnectionType() == VpnAccountData::ciscoorig)
                            type = "ciscoorig" ;
                        else if (it->getConnectionType() == VpnAccountData::racoon)
                            type = "racoon" ;
                        else if (it->getConnectionType() == VpnAccountData::l2tpd_racoon)
                            type = "l2tpd (racoon)" ;
                        else if (it->getConnectionType() == VpnAccountData::freeswan)
                            type = "freeswan" ;
                        else if (it->getConnectionType() == VpnAccountData::l2tpd_freeswan)
                            type = "l2tpd (openswan)" ;
                        else if (it->getConnectionType() == VpnAccountData::pptp)
                            type = "pptp" ;
                        else if (it->getConnectionType() == VpnAccountData::openvpn)
                            type = "openvpn" ;
                        else
                            type =  i18n("other");


                        values << name << type << it->getGateway();

                        // FIXME how i can made this checkable?
                        QTreeWidgetItem *listitem = new QTreeWidgetItem((QTreeWidget*)0, values);
                        listitem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
                        listitem->setData(0, Qt::CheckStateRole, Qt::Unchecked);
                        items.append(listitem);
                        values.clear();
                    }
                    selectdlg.ImportProfileListView->addTopLevelItems( items);
					selectdlg.ImportNamePrefixLineEdit->setText( "kvpnc_import_");
                }
                bool ret = selectdlg.exec();

                if (ret == true) {
                    importGlobal = selectdlg.ImportGlobalSettingsCheckBox->isChecked();
                    QTreeWidgetItemIterator it2(selectdlg.ImportProfileListView);
                    while (*it2) {
                        VpnAccountData *data = NULL;
                        it = 0;
                        for (int accountIdx = 0; accountIdx < ImportedAccountList->size(); ++accountIdx) {
                            it = ImportedAccountList->at(accountIdx);
                            if (it->getName() == (*it2)->text(0) && (*it2)->data(0, Qt::CheckStateRole).toInt() == Qt::Checked) {
                                if (KvpncDebugLevel > 2)
                                    appendLogEntry(i18n("Profile marked for import: %1", it->getName()) , KVpncEnum::debug);
                                data = it;
                                importCount++;

								data->setName(selectdlg.ImportNamePrefixLineEdit->text()+data->getName());
								
								bool ok = false;
								VpnAccountData * it;
								bool nameOk = false;
								while ( nameOk == false ) {
									for (int accountIdx = 0; accountIdx < AccountList->size(); ++accountIdx) {
										it = AccountList->at(accountIdx);
										if ( it->getName() == data->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 ( 0, i18n ( "Profile name exists!" ), i18n ( "Name Exists" ) );
											nameOk = false;
											QString newName = KInputDialog::getText ( i18n ( "New Name" ), i18n ( "New name for profile:" ), QString ( data->getName() + "_2" ), &ok );
											if (newName.isEmpty()) {
												KMessageBox::information ( 0, i18n ( "Import was canceled." ) );
												appendLogEntry ( i18n ( "Import of profile %1 was canceled.", data->getName() ), KVpncEnum::info );
												continue;
											}
											if (newName != it->getName() ) {
												data->setName ( newName );
												nameOk = true;
											}
										} else {
											nameOk = true;
										}
									}
								}
								
								if ( nameOk == true ) {
									AccountList->append(data);
									RetName = data->getName();
								}
                            }
                        }
                        ++it2;
                    }
                    if (selectdlg.OpenProfileManagerCheckBox->isChecked())
                        openProfileManager = true;
                } else {
                    KMessageBox::sorry(0, i18n("Import canceled."), i18n("Canceled"));
                    return false;
                }
            }
            n = n.nextSibling();
        }

        if (importGlobal == true) {
            this-> pathToVpnc = pathToVpnc;
            this-> pathToCiscoVpnc = pathToCiscoVpnc;
            this-> pathToRacoon = pathToRacoon;
            this-> pathToSetkey = pathToSetkey;
            this-> pathToIptables = pathToIptables;
            this-> pathToIpsec = pathToIpsec;
            this-> pathToPppd = pathToPppd;
            this-> pathToPptp = pathToPptp;
            this-> pathToL2tpd = pathToL2tpd;
            this-> pathToXl2tpd = pathToXl2tpd;
            this-> pathToSsh = pathToSsh;
            this-> pathToKill = pathToKill;
            this-> pathToKillall = pathToKillall;
            this-> pathToPing = pathToPing;
            this-> pathToOpenvpn = pathToOpenvpn;
            this-> pathToIp = pathToIp;
            this-> pathToIfconfig = pathToIfconfig;
            this-> pathToRoute = pathToRoute;
            this-> pathToNetstat = pathToNetstat;
            this-> pathToPkcs11Tool = pathToPkcs11Tool;
            this-> AutoConnectProfile = AutoConnectProfile;
            this-> RacoonDebugLevel = RacoonDebugLevel;
            this-> Vpnc_pid_file = Vpnc_pid_file;
            this-> Pppd_pid_file = Pppd_pid_file;
            this-> lastProfile = lastProfile;
            this-> logfileName = logfileName;
            this->minimizeAfterConnect = minimizeAfterConnect;
            this->showDebugConsole = showDebugConsole;
            this-> writeLogFile = writeLogFile;
            this-> useDefaultPaths = useDefaultPaths;
            this-> useSilentQuit = useSilentQuit;
            this-> holdGeneratedScripts = holdGeneratedScripts;
            this-> programsInPath = programsInPath;
            this-> enableDebugPppd = enableDebugPppd;
            this-> enableDebugPptpd = enableDebugPptpd;
            this-> enableDebugL2tpd = enableDebugL2tpd;
            this-> enableDebugXl2tpd = enableDebugXl2tpd;
            this-> enableFreeswanVerbose = enableFreeswanVerbose;
            this-> enableDebugOpenvpn = enableDebugOpenvpn;
            this-> useColorizedLogOutput = useColorizedLogOutput;
            this-> showInterfaceIPinTooltip = showInterfaceIPinTooltip;
            this-> dontQuitOnCloseEvent = dontQuitOnCloseEvent;
            this-> doAutoConnectAtStartup = doAutoConnectAtStartup;
            this-> useKwallet = useKwallet;
            this-> showStatusBar = showStatusBar;
            this-> showToolBar = showToolBar;
            this-> hideMainWindow = hideMainWindow;
            this-> PppdDebugLevel = PppdDebugLevel;
            this-> firstUseOfKwallet = firstUseOfKwallet;
            this-> shutdownIsCalled = shutdownIsCalled;
            this-> skipKwalletStoring = skipKwalletStoring;
            this-> hideOnCloseInfo = hideOnCloseInfo;
            this-> feedbackMailSent = feedbackMailSent;
            this-> doKillL2tpdIfStillRunning = doKillL2tpdIfStillRunning;
            this-> doKillXl2tpdIfStillRunning = doKillXl2tpdIfStillRunning;
            this-> doKillRacoonIfStillRunning = doKillRacoonIfStillRunning;
            this-> showConnectionTimeInTooltip = showConnectionTimeInTooltip;
            this-> VpncDebugLevel = VpncDebugLevel;
            this-> KvpncDebugLevel = KvpncDebugLevel;
            this-> OpenvpnDebugLevel = OpenvpnDebugLevel;
            this-> PptpLogLevel = PptpLogLevel;
            this-> SshDebugLevel = SshDebugLevel;
            this-> LogViewerFontSize = LogViewerFontSize;
            this-> mainwindow_pos_x = mainwindow_pos_x;
            this-> mainwindow_pos_y = mainwindow_pos_y;
            this-> mainwindow_height = mainwindow_height;
            this-> mainwindow_width = mainwindow_width;
            this-> connectSleepDelay = connectSleepDelay;
            this-> connectSleepRetry = connectSleepRetry;
            this-> tryConnectTimeout = tryConnectTimeout;
            this-> connectionStartTime = connectionStartTime;
            this-> runningCheckCounter = runningCheckCounter;
            this-> runningCheckTimeout = runningCheckTimeout;
            this-> OpenvpnManagementPort = OpenvpnManagementPort;
            this->InfoLogColor = InfoLogColor;
            this->RemoteLogColor = RemoteLogColor;
            this->ErrorLogColor = ErrorLogColor;
            this->SuccessLogColor = SuccessLogColor;
            this->DebugLogColor = DebugLogColor;
            this->DebugBackgroundcolor = DebugBackgroundcolor;
            this->pos = pos;
            this->WindowPos = WindowPos;
            this->WindowSize = WindowSize;

        }
        saveOptions();

        QString msg = "";
        if (importCount > 0 && importGlobal == true)
            msg = i18np("Import was successful. %1 profile and global settings were imported.", "Import was successful. %1 profiles and global settings were imported.", importCount);
        if (importCount > 0 && importGlobal == false)
            msg = i18np("Import was successful. %1 profile was imported.", "Import was successful. %1 profiles were imported.", importCount);
        if (importCount < 1 && importGlobal == true)
            msg = i18n("Import was successful. Global settings were imported.");
		if (importCount < 1 && importGlobal == false)
			msg = i18n("Import was successful. Nothing was imported.");
        KMessageBox::information(0, msg, i18n("Import success"));
    } else {
        KMessageBox::error(0, i18n("Failed to read \"%1\"." ,   filename));
        appendLogEntry(i18n("Failed to read \"%1\"." , filename), KVpncEnum::error);
        QApplication::restoreOverrideCursor();
        return false;
    }
    return true;
}

bool KVpncConfig::importIpsecConfig(QString filename, QString& RetName, bool& openProfileManager)
{
    QFile importfile(filename);
    if (!importfile.exists()) {
        KMessageBox::error(0, i18n("Failed to read \"%1\"." ,   filename));
        return false;
    }
    QList<VpnAccountData *> *ImportedAccountList = new QList<VpnAccountData *>();
    QList<IpsecImportSection *> *IpsecImportSectionList = new QList<IpsecImportSection*>();

    bool isIpsecGlobalSection = false;
    bool firstSectionFound = false;
    bool defaultSectionFound = false;
    bool useNat = false;
    bool disableOpportunisticEncryption = true;
    QStringList InterfaceList;
    int IpsecVersion = 1;
//  bool pskIsInFile=true;
    QString PskFile = "/etc/ipsec.secrets";
    QString CertPath = "/etc/ipsec.d/certs";

    QString IpsecConfigSection = "";
    bool validLineFound = false;
    if (importfile.open(QIODevice::ReadOnly)) {
        QString line = NULL;
        QString IpsecConfigSectionName = "";
        QString IpsecConfigData = "";
        bool sectionEndFound = false;

        if (KvpncDebugLevel > 2)
            appendLogEntry(i18n("Import ipsec config: pass1: collecting sections"), KVpncEnum::debug);
        QTextStream stream(&importfile);
        while (!stream.atEnd()) {
            line = stream.readLine().replace("\"", "");

            if (IpsecConfigSectionName != "" && (line == "\n" || removeWhiteSpaceAtBegin(line) == "\n" ||  line == NULL || line.startsWith("include") || line.startsWith("conn"))) {
                // end of section found
                if (KvpncDebugLevel > 2)
                    appendLogEntry(i18n("Import ipsec config: end of section %1 found.", IpsecConfigSectionName), KVpncEnum::debug);

                sectionEndFound = true;

                IpsecImportSection *section = new IpsecImportSection();
                section->SectionName = IpsecConfigSectionName;
                section->SectionData = QStringList(IpsecConfigData);
                IpsecImportSectionList->append(section);
                IpsecConfigData = "";
                IpsecConfigSectionName = "";

                if (KvpncDebugLevel > 2) {
                    appendLogEntry("import ipsec config: Section:", KVpncEnum::debug);
                    appendLogEntry(section->SectionName , KVpncEnum::debug);
                    appendLogEntry(section->SectionData.join("\n"), KVpncEnum::debug);
                    appendLogEntry("-------------------", KVpncEnum::debug);
                }
            }

            if (line.startsWith("conn")) {
                // section found
                IpsecConfigSectionName = line.simplified().section('#', 0, 0).section(" ", 1, 1);

                isIpsecGlobalSection = false;

                if (IpsecConfigSectionName == "%default") {
                    defaultSectionFound = true;
                    sectionEndFound = false;
                    firstSectionFound = true;
                    if (KvpncDebugLevel > 2)
                        appendLogEntry(i18n("Import ipsec config: default section found."), KVpncEnum::debug);
                } else {
                    if (KvpncDebugLevel > 2)
                        appendLogEntry(i18n("Import ipsec config: normal section found: ") + IpsecConfigSectionName , KVpncEnum::debug);
                    sectionEndFound = false;
                    firstSectionFound = true;
                }
            }
            if (line.startsWith("version")) {
                IpsecVersion = int (QString(line.simplified().section('#', 0, 0).section(" ", 1, 1).trimmed()).toFloat());
                validLineFound = true;
                if (KvpncDebugLevel > 2)
                    appendLogEntry(i18n("Import ipsec config: ipsec version found: ") + QString().setNum(IpsecVersion) , KVpncEnum::debug);
            }
            if (line.startsWith("config setup")) {
                // config section found
                isIpsecGlobalSection = true;
                validLineFound = true;
                if (KvpncDebugLevel > 2)
                    appendLogEntry(i18n("Import ipsec config: global section found."), KVpncEnum::debug);
            }

            if (isIpsecGlobalSection == true) {
                QString line2 = removeWhiteSpaceAtBegin(line);
                if (line2.startsWith("plutodebug")) {
                    validLineFound = true;
                    // FIXME not implemented yet
                }
                if (line2.startsWith("nat_traversal=")) {
                    validLineFound = true;
                    useNat = false;
                    if (line2.section('=', 1, 1) == "yes") {
                        useNat = true;
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Import ipsec config: use NAT."), KVpncEnum::debug);
                    } else {
                        useNat = false;
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Import ipsec config: do not use NAT."), KVpncEnum::debug);
                    }
                }

                if (line2.startsWith("interfaces=")) {
                    validLineFound = true;
                    if (line2.section('=', 1, 1) == "%defaultroute") {
                        InterfaceList.append("default");
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Import ipsec config: use interface to which default route points."), KVpncEnum::debug);
                    } else {
                        InterfaceList = line2.replace("interfaces=", "").replace(QRegExp("ipsec[0-9]="), "").split(QChar(' '));
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Import ipsec config: use interface from list:") + " " + InterfaceList.join(", "), KVpncEnum::debug);
                    }
                }
            }

            if (line.startsWith("include /etc/ipsec.d/examples/no_oe.conf")) {
                validLineFound = true;
                isIpsecGlobalSection = false;
                if (KvpncDebugLevel > 2)
                    appendLogEntry(i18n("Import ipsec config: opportunistic encrytion disabled found"), KVpncEnum::debug);

                disableOpportunisticEncryption = true;
            }

            if (!sectionEndFound && firstSectionFound == true) {
                // collecting data
                QString cleanLine = removeWhiteSpaceAtBegin(line) + "\n";
                if (!cleanLine.startsWith("#") && !cleanLine.startsWith("include")  && cleanLine != ""  && !line.startsWith("conn") && cleanLine != "\n") {
                    IpsecConfigData.append(line + "\n");
                }
            }
        }
        importfile.close();
        if (IpsecConfigSectionName != "") {
            // end of section found
            if (KvpncDebugLevel > 2)
                appendLogEntry("end of section " + IpsecConfigSectionName + " found.", KVpncEnum::debug);
            sectionEndFound = true;

            IpsecImportSection *section = new IpsecImportSection();
            section->SectionName = IpsecConfigSectionName;
            section->SectionData = QStringList(IpsecConfigData);
            IpsecImportSectionList->append(section);
            IpsecConfigData = "";
            IpsecConfigSectionName = "";
        }

        


        if (KvpncDebugLevel > 2)
            appendLogEntry(i18n("Import ipsec config: pass2: modify sections"), KVpncEnum::debug);

        if (KvpncDebugLevel > 2)
            appendLogEntry(i18n("Import ipsec config: sections: ") + QString().setNum(IpsecImportSectionList->count()), KVpncEnum::debug);

        if (!IpsecImportSectionList->isEmpty()) {
            for (int i = 0; i < (int) IpsecImportSectionList->count();i++) {
                IpsecImportSection *section = IpsecImportSectionList->at(i);
                QString Name = section->SectionName;
                QStringList data =  section->SectionData.join("\n").split(QChar('\n'));

                if (Name != "%default") {
                    if (KvpncDebugLevel > 2)
                        appendLogEntry(i18n("Import ipsec config: => processing section: ") + "\"" + Name + "\"", KVpncEnum::debug);

                    for (QStringList::Iterator it2 = data.begin(); it2 != data.end(); ++it2) {
                        QString dataline = *it2;
                        if (removeWhiteSpaceAtBegin(dataline).startsWith("also=")) {
                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Import ipsec config: also= found, looking for other section..."), KVpncEnum::debug);

                            QString newdata = QString(section->SectionData.join("\n"));
                            newdata.replace(QRegExp("^.*also=.*$"), "");
                            section->SectionData = newdata.split(QChar('\n'));

                            QString OtherSection = dataline.simplified().section('#', 0, 0).section("=", 1, 1);
                            // we have to find the other section and replace this line by the config data of the other section (after the =)
                            bool section_found = false;
                            for (int accountIdx = 0; accountIdx < IpsecImportSectionList->size(); ++accountIdx) {
                                IpsecImportSection * it3 = IpsecImportSectionList->at(accountIdx);
                                if (it3->SectionName == OtherSection) {
                                    if (KvpncDebugLevel > 2)
                                        appendLogEntry(i18n("Import ipsec config: section %1 found, appending:", OtherSection), KVpncEnum::debug);
                                    section_found = true;
                                    //         data.remove(dataline);
                                    dataline = "";
                                    //         QStringList otherdata = QString(it3->SectionData.join("\n")).split(QString("\n"));
                                    QString OtherData = QString(it3->SectionData.join("\n"));

                                    QStringList newdata;

                                    for (QStringList::Iterator it6 = data.begin(); it6 != data.end(); ++it6) {
                                        if (KvpncDebugLevel > 2)
                                            appendLogEntry(i18n("Import ipsec config: also line: ") + QString(*it6), KVpncEnum::debug);

                                        if (QString(*it6).indexOf(QString("also="), 0, Qt::CaseInsensitive) < 0) {
                                            if (KvpncDebugLevel > 2)
                                                appendLogEntry(i18n("Import ipsec config: also= found."), KVpncEnum::debug);
                                            newdata.append(QString(*it6));
                                        } else {
                                            if (KvpncDebugLevel > 2)
                                                appendLogEntry(i18n("Import ipsec config: also= not found.") , KVpncEnum::debug);
                                        }
                                    }
                                    //         newdata.append(data.join("\n"));
                                    newdata.append(OtherData);
                                    section->SectionData = newdata;

                                }
                            }
                            if (!section_found) {
                                if (KvpncDebugLevel > 2)
                                    appendLogEntry(i18n("Import ipsec config: section %1 not found, skipping", OtherSection) , KVpncEnum::debug);
                            }

                        }
                    }

                    if (defaultSectionFound == true) {
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Import ipsec config: => default section is set... "), KVpncEnum::debug);

                        for (int i = 0; i < (int) IpsecImportSectionList->count();i++) {
                            IpsecImportSection *section2 = IpsecImportSectionList->at(i);
                            QString Name = section2->SectionName;
                            if (Name == "%default") {

                                if (KvpncDebugLevel > 2)
                                    appendLogEntry(i18n("Import ipsec config: => appending %default section: ") + "\"" + section2->SectionData.join("\n") , KVpncEnum::debug);

                                QStringList defaultdata = section2->SectionData.join("\n").split(QChar('\n'));


                                for (QStringList::Iterator defaultit = defaultdata.begin(); defaultit != defaultdata.end(); ++defaultit) {
                                    if (KvpncDebugLevel > 2)
                                        appendLogEntry(i18n("Import ipsec config: => appending %default line: ") + "\"" + *defaultit, KVpncEnum::debug);
                                    section->SectionData.append(*defaultit);
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }

//   IpsecImportSection *it5=NULL;
//   for ( it5 = IpsecImportSectionList->first(); it5; it5 = IpsecImportSectionList->next() )
//   {
//    QString SectionName= it5->SectionName;
//    QStringList data = it5->SectionData;
//   }

        // remove default section
        for (int i = 0; i < (int) IpsecImportSectionList->count();i++) {
            IpsecImportSection *section = IpsecImportSectionList->at(i);
            QString Name = section->SectionName;
            if (Name == "%default") {
                IpsecImportSectionList->removeAll(IpsecImportSectionList->at(i));
                break;
            }
        }

        if (KvpncDebugLevel > 2) {
            appendLogEntry("modified config" , KVpncEnum::debug);
            appendLogEntry("---------------------" , KVpncEnum::debug);
            IpsecImportSection *it5 = NULL;
            for (int accountIdx = 0; accountIdx < IpsecImportSectionList->size(); ++accountIdx) {
                it5 = IpsecImportSectionList->at(accountIdx);
                QString SectionName = it5->SectionName;
                QStringList data = it5->SectionData;

                appendLogEntry(SectionName  , KVpncEnum::debug);
                appendLogEntry(data.join("\n")  , KVpncEnum::debug);
            }
        }

        if (KvpncDebugLevel > 2)
            appendLogEntry("import ipsec config: pass3: parse sections" , KVpncEnum::debug);

        if (!IpsecImportSectionList->isEmpty()) {
            for (int i = 0; i < (int) IpsecImportSectionList->count();i++) {
                IpsecImportSection *section = IpsecImportSectionList->at(i);

                QStringList sectiondata = section->SectionData.join("\n").split(QChar('\n'));

                if (KvpncDebugLevel > 2)
                    appendLogEntry("import ipsec config:   => processing section: \"" + section->SectionName + "\"" , KVpncEnum::debug);

                VpnAccountData *profiledata = new VpnAccountData(VpnAccountData::freeswan, QString(section->SectionName)) ;

                QList<QString>::iterator it2;
                for (it2 = sectiondata.begin(); it2 != sectiondata.end() ; ++it2) {
                    QString dataline = *it2;
                    QString line2 = removeWhiteSpaceAtBegin(dataline);  // line of text excluding '\n' and replace all white chars with one blank
                    if (line2.startsWith("rightsubnet=")) {
                        validLineFound = true;
                        QString RightSubnet = line2.section ( "rightsubnet=",1,-1 );
                        if (KvpncDebugLevel > 2)
                            appendLogEntry("import ipsec config: right subnet (remote) found: " + RightSubnet , KVpncEnum::debug);
                        profiledata->setRemoteNetAddr(RightSubnet.section('/', 0, 0));
                        profiledata->setRemoteNetMask(RightSubnet.section('/', 1, 1));

                        profiledata->setUseRemoteNetwork(true);
                        //       if (KvpncDebugLevel > 2)
                        //        appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("leftsubnet=")) {
                        validLineFound = true;
                        QString LeftSubnet = line2.section ( "leftsubnet=",1,-1 );
                        if (KvpncDebugLevel > 2)
                            appendLogEntry("import ipsec config: left subnet (local) found: " + LeftSubnet , KVpncEnum::debug);
                        //      local subnet cant be set yet.
                        //      profiledata->setLocalNetAddr(RightSubnet.section('/',0,0));
                        //      profiledata->setLocalNetMask(RightSubnet.section('/',1,1));

                    }
                    if (line2.startsWith("rightnexthop=")) {
                        validLineFound = true;
                        QString RightNextHop = line2.section ( "rightnexthop=",1,-1 );
                        if (KvpncDebugLevel > 2)
                            appendLogEntry("import ipsec config: right next hop (remote) found: " + RightNextHop , KVpncEnum::debug);
                        profiledata->setRightNextHop(RightNextHop);
                        profiledata->setUseRightNextHop(true);
                        //if (KvpncDebugLevel > 2)
                        //	appendLogEntry("import freeswan config: => set it for profile " + qPrintable(IpsecConfigSection) + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("leftnexthop=")) {
                        validLineFound = true;
                        QString LeftNextHop = line2.section ( "leftnexthop=",1,-1 );
                        if (KvpncDebugLevel > 2)
                            appendLogEntry("import ipsec config: left next hop (local) found: " +LeftNextHop , KVpncEnum::debug);
                        profiledata->setLeftNextHop(LeftNextHop);
                        profiledata->setUseLeftNextHop(true);
                        if (KvpncDebugLevel > 2)
                            appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("left=")) {
                        validLineFound = true;
                        QString left = line2.section ( "left=",1,-1 );
                        //      local ip cant be set yet.
                        //        if (KvpncDebugLevel > 2)
                        //         appendLogEntry("import ipsec config: left found: " + left , KVpncEnum::debug);
                        //      profiledata->setLocal (left);
                        //       if (KvpncDebugLevel > 2)
                        //        appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("right=")) {
                        validLineFound = true;
                        QString right = line2.section ( "right=",1,-1 );
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Import ipsec config: right (remote gateway) found: ") + right , KVpncEnum::debug);
                        profiledata->setGateway(right);
                        //       if (KvpncDebugLevel > 2)
                        //        appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("leftcert=")) {
                        validLineFound = true;
                        QString LeftCert = line2.section ( "leftcert=",1,-1 );
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Import ipsec config: left cert (local) found: ") + LeftCert , KVpncEnum::debug);
                        profiledata->setX509Certificate(LeftCert);
                        //if (KvpncDebugLevel > 2)
                        //	appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("rightcert=")) {
                        validLineFound = true;
                        QString RightCert = line2.section("rightcert=",1,-1);
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Import ipsec config: right cert (remote) found: ") + RightCert , KVpncEnum::debug);
                        profiledata->setUseSpecialServerCertificate(true);
                        profiledata->setSpecialServerCertificate(RightCert);
                        //if (KvpncDebugLevel > 2)
                        //	appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("rightca=")) {
                        validLineFound = true;
                        QString RightCA = line2.section ( "rightca=",1,-1 );
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Import ipsec config: right CA (remote) found: ") + RightCA , KVpncEnum::debug);
                        profiledata->setCaCertificate(RightCA);
                        //if (KvpncDebugLevel > 2)
                        //	appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("rightid=")) {
                        validLineFound = true;
                        QString RightID = line2.section ( "rightid=",1,-1 );
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Import ipsec config: right ID (remote) found: ") + RightID , KVpncEnum::debug);
                        profiledata->setUseSpecialRemoteID(true);
                        profiledata->setSpecialRemoteID(RightID);
                        profiledata->setRemoteIDType("keyid");
                        //if (KvpncDebugLevel > 2)
                        //	appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("leftid=")) {
                        validLineFound = true;
                        QString LeftID = line2.section ( "leftid=",1,-1 );
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Import ipsec config: local ID (local) found: ") + LeftID , KVpncEnum::debug);
                        profiledata->setUseSpecialLocalID(true);
                        profiledata->setSpecialLocalID(LeftID);
                        profiledata->setLocalIDType("keyid");
                        //if (KvpncDebugLevel > 2)
                        //	appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("rightrsasigkey=")) {
                        validLineFound = true;
                        QString RightRsaSigKey = line2.section ( "rightrsasigkey=",1,-1 );
                        if (RightRsaSigKey == "%cert") {
                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Import ipsec config: right (remote) uses cert"), KVpncEnum::debug);
                            profiledata->setAuthType(VpnAccountData::cert);
                        } else {

                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Import ipsec config: right (remote) uses ") + RightRsaSigKey , KVpncEnum::debug);
                            profiledata->setAuthType(VpnAccountData::psk);

							// ok, we use special server cert here because at psk its unused
							profiledata->setSpecialServerCertificate( RightRsaSigKey );
							profiledata->setUseSpecialServerCertificate(true);
                        }
                        //if (config->KvpncDebugLevel > 2)
                        //	appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("leftrsasigkey=")) {
                        validLineFound = true;
                        QString LeftRsaSigKey = line2.section ( "leftrsasigkey=",1,-1 );
                        if (LeftRsaSigKey == "%cert") {
                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Import ipsec config: left (local) uses cert"), KVpncEnum::debug);
                            profiledata->setAuthType(VpnAccountData::cert);

                        } else {

                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Import ipsec config: left (local) uses ") + LeftRsaSigKey , KVpncEnum::debug);
                            profiledata->setAuthType(VpnAccountData::psk);

                            profiledata->setPreSharedKeyFile(LeftRsaSigKey);
                            profiledata->setPskIsInFile(true);
                        }
                        //if (KvpncDebugLevel > 2)
                        //	appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("authby=")) {
                        validLineFound = true;
                        QString Authby = line2.section ( "authby=",1,1 );
                        if (Authby.indexOf("rsasig", 0 , Qt::CaseInsensitive) > -1) {
                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Import ipsec config: left and right use certs.") , KVpncEnum::debug);
                            profiledata->setAuthType(VpnAccountData::cert);
                            profiledata->setCertPath("/etc/ipsec.d/certs");
                            //profiledata->setPskIsInFile(true);
                            //profiledata->setPrivateKey("/etc/ipsec.secrets");
                        } else if (Authby.indexOf("secret", 0 , Qt::CaseInsensitive) > -1) {
                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Import ipsec config: left and right use psk.") , KVpncEnum::debug);
                            profiledata->setAuthType(VpnAccountData::psk);
                            //profiledata->setPskIsInFile(true);
                            //profiledata->setPreSharedKeyFile("/etc/ipsec.secrets");
                        } else {
                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Import ipsec config: left and right use unknown auth, guess psk") , KVpncEnum::debug);
                            profiledata->setAuthType(VpnAccountData::psk);
                        }

                        //if (KvpncDebugLevel > 2)
                        //	appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("auto=start")) {
                        //      validLineFound=true;
                        //      QString Authby=line2.simplified().section('#',0,0).section("=",1,1);
                        //       if (KvpncDebugLevel > 2)
                        //        appendLogEntry("import ipsec config: profile should be started" , KVpncEnum::debug);
                        //      profiledata->setAuthType(VpnAccountData::cert);
                        //       if (KvpncDebugLevel > 2)
                        //        appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("leftsourceip=")) {
                        validLineFound = true;
                        QString leftsourceip = line2.section ( "leftsourceip=",1,-1 );
                        std::cout << "left (local) have to use IP address " << leftsourceip.ascii() << std::endl;
                        if (KvpncDebugLevel > 2)
                            appendLogEntry("import ipsec config: left (local) have to use IP address " + leftsourceip ,KVpncEnum::debug);
                        profiledata->setLocalVirtualIP(leftsourceip);
                        //std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
                        if (KvpncDebugLevel > 2)
                            appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." ,KVpncEnum::debug);
                    }
                    if (line2.startsWith("virtual_private=")) {
                        validLineFound = true;
                        QString virtualprivate = line2.section ( "virtual_private=",1,-1 );
                        if (KvpncDebugLevel > 2)
                            appendLogEntry("import ipsec config: virtual private networks " + virtualprivate , KVpncEnum::debug);
                        profiledata->setLocalVirtualIP(virtualprivate);
                        profiledata->setUseVirtualIP(true);
                        if (KvpncDebugLevel > 2)
                            appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("rightsourceip=")) {
                        validLineFound = true;
                        QString rightsourceip = line2.section ( "rightsourceip=",1,-1 );
                        if (KvpncDebugLevel > 2)
                            appendLogEntry("import ipsec config: right (remote) have to use IP address " + rightsourceip , KVpncEnum::debug);
                        profiledata->setRightSourceIp(rightsourceip);
                        profiledata->setUseRightSourceIp(true);
                        if (KvpncDebugLevel > 2)
                            appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("esp=")) {
                        validLineFound = true;
                        QString IpsecEsp = line2.section ( "esp=",1,-1 );
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Import ipsec config: esp settings found: ") + IpsecEsp , KVpncEnum::debug);
                        profiledata->setIpsecEsp(IpsecEsp);
                        profiledata->setUseCustomEsp(true);
                        //if (KvpncDebugLevel > 2)
                        //	appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("ike=")) {
                        validLineFound = true;
                        QString IpsecIke = line2.section ( "ike=",1,-1 );
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Import ipsec config: ike settings found: ") + IpsecIke , KVpncEnum::debug);
                        profiledata->setIpsecIke(IpsecIke);
                        profiledata->setUseCustomIke(true);
                        //if (KvpncDebugLevel > 2)
                        //	appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("type=")) {
                        validLineFound = true;
                        QString IpsecVpnMode = line2.section ( "type=",1,1 );
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Import ipsec config: IPsec vpn mode found: ") + IpsecVpnMode , KVpncEnum::debug);
                        if (IpsecVpnMode == "tunnel")
                            profiledata->setIpsecVpnMode("tunnel");
                        else
                            profiledata->setIpsecVpnMode("transport");
                        //if (KvpncDebugLevel > 2)
                        //	appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("leftxauthclient=")) {
                        validLineFound = true;
                        QString useXauth = line2.section ( "leftxauthclient=",1,1 );
                        if (useXauth == "yes") {
                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Use XAUTH (leftxauthclient found):") + " " + i18n("yes") , KVpncEnum::debug);
                            profiledata->setAuthWithUsernameAndPassword(true);
                        } else {
                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Use XAUTH (leftxauthclient found):") + " " + i18n("no") , KVpncEnum::debug);
                            profiledata->setAuthWithUsernameAndPassword(false);
                        }
                        //if (KvpncDebugLevel > 2)
                        //	appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." ,KVpncEnum::debug);
                    }
                    if (line2.startsWith("rightxauthserver=")) {
                        validLineFound = true;
                        QString  useXauth = line2.section ( "rightxauthserver=",1,-1 );
                        if (useXauth == "yes") {
                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Use XAUTH (rightxauthserver found):") + " " + i18n("yes") , KVpncEnum::debug);
                            profiledata->setAuthWithUsernameAndPassword(true);
                        } else {
                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Use XAUTH (rightxauthserver found):") + " " + i18n("no") , KVpncEnum::debug);
                            profiledata->setAuthWithUsernameAndPassword(false);
                        }
                        //if (KvpncDebugLevel > 2)
                        //	appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." ,KVpncEnum::debug);
                    }
                    if (line2.startsWith("keyingtries=")) {
                        validLineFound = true;
                        int MaxConnectTries = QString(line2.section ( "keyingtries=",1,1 )).toInt();
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Import ipsec config: keyingtries found: ") + QString().setNum(MaxConnectTries) , KVpncEnum::debug);
                        profiledata->setMaxConnectTries(MaxConnectTries);
                        //if (KvpncDebugLevel > 2)
                        //	appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." ,KVpncEnum::debug);
                    }
                    if (line2.startsWith("pfs=")) {
                        validLineFound = true;
                        QString UsePerfectForwardSecrety = line2.section ( "pfs=",1,1 ).remove ( '"' );
                        if (UsePerfectForwardSecrety == "yes") {
                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Use PFS:") + " " + i18n("yes") , KVpncEnum::debug);
                            profiledata->setUsePerfectForwardSecrety(true);
                        } else {
                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Use PFS:") + " " + i18n("no") , KVpncEnum::debug);
                            profiledata->setUsePerfectForwardSecrety(false);
                        }
                        //if (KvpncDebugLevel > 2)
                        //	appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." ,KVpncEnum::debug);
                    }
                    if (line2.startsWith("pfsgroup=")) {
                        validLineFound = true;
                        QString PerfectForwardSecrety = line2.section ( "pfsgroup=",1,1 );
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Import ipsec config: PFS group found: ") + PerfectForwardSecrety , KVpncEnum::debug);
                        profiledata->setPerfectForwardSecrety(PerfectForwardSecrety);
                        //if (KvpncDebugLevel > 2)
                        //	appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." ,KVpncEnum::debug);
                    }
                    if (line2.startsWith("aggrmode=")) {
                        validLineFound = true;
                        QString UseAgressiveMode = line2.section ( "aggrmode=",1,1 ).remove ( '"' );
                        if (UseAgressiveMode == "yes") {
                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Exchange mode:") + " " + "aggressive" , KVpncEnum::debug);
                            profiledata->setExchangeMode("aggressive");
                        } else {
                            if (KvpncDebugLevel > 2)
                                appendLogEntry(i18n("Exchange mode:") + " " + "main" , KVpncEnum::debug);
                            profiledata->setExchangeMode("main");
                        }
                        //if (KvpncDebugLevel > 2)
                        //	appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." ,KVpncEnum::debug);
                    }
                }

                if (useNat) {
                    profiledata->setUseNat(true);
                    if (KvpncDebugLevel > 2)
                        appendLogEntry(i18n("Import ipsec config: nat_traversal=yes found, enabling nat.") , KVpncEnum::debug);
                } else {
                    profiledata->setUseNat(false);
                    if (KvpncDebugLevel > 2)
                        appendLogEntry(i18n("Import ipsec config: nat_traversal=no found, disabling nat.") , KVpncEnum::debug);
                }
                if (disableOpportunisticEncryption ==  true) {
                    profiledata->setDisableOpportunisticEncryption(true);
                } else {
                    profiledata->setDisableOpportunisticEncryption(false);
                }

                // FIXME we only use the first in list
                if (InterfaceList.isEmpty())
                    InterfaceList.append("default");
                QString Interface = InterfaceList.first();
                profiledata->setNetworkDevice(Interface);

                profiledata->setName("kvpnc_import_" + profiledata->getName());
                profiledata->setDescription(QString(i18n("import from ") + filename));
                ImportedAccountList->append(profiledata);
            }
        }


        KvpncImportProfileSelectionDialog selectdlg(0);
        selectdlg.ImportGlobalSettingsCheckBox->hide();
        VpnAccountData *it = NULL;
        QList<QTreeWidgetItem *> items;
        QStringList values;
        int importCount = 0;

        if (!ImportedAccountList->isEmpty()) {
            selectdlg.ImportProfileListView->setColumnCount(5);
            QStringList LabelList;
            LabelList << i18n("Name") << i18n("Type") << i18n("Gateway") << i18n("Authentication") << i18n("Remote network");
            selectdlg.ImportProfileListView->setHeaderLabels(LabelList);

            for (int accountIdx = 0; accountIdx < ImportedAccountList->size(); ++accountIdx) {
                it = ImportedAccountList->at(accountIdx);
                QString name = it->getName();
                QString type = "";

                values << name;

                if (it->getConnectionType() == VpnAccountData::cisco)
                    type = "cisco" ;
                else if (it->getConnectionType() == VpnAccountData::ciscoorig)
                    type = "ciscoorig" ;
                else if (it->getConnectionType() == VpnAccountData::racoon)
                    type = "racoon" ;
                else if (it->getConnectionType() == VpnAccountData::l2tpd_racoon)
                    type = "l2tpd (racoon)" ;
                else if (it->getConnectionType() == VpnAccountData::freeswan)
                    type = "ipsec" ;
                else if (it->getConnectionType() == VpnAccountData::l2tpd_freeswan)
                    type = "l2tpd (ipsec)" ;
                else if (it->getConnectionType() == VpnAccountData::pptp)
                    type = "pptp" ;
                else if (it->getConnectionType() == VpnAccountData::openvpn)
                    type = "openvpn" ;
                else
                    type =  i18n("other");

                values << type << it->getGateway();

                if (it->getAuthType() == VpnAccountData::cert)
                    values << i18n("certificate");
                else if (it->getAuthType() == VpnAccountData::psk)
                    values << i18n("preshared key");
                else if (it->getAuthType() == VpnAccountData::hybrid)
                    values << i18n("hybrid");
                else
                    values << i18n("unknown");

                QString RemoteNetDiv = "/";
                if (it->getRemoteNetAddr().isEmpty()) {
                    RemoteNetDiv=QString("");
                    it->setRemoteNetMask(QString(""));
                }
                values << QString(it->getRemoteNetAddr() + RemoteNetDiv + it->getRemoteNetMask());



                QTreeWidgetItem *listitem = new QTreeWidgetItem((QTreeWidget*)0, values);
                listitem->setFlags( Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
                listitem->setData(0, Qt::CheckStateRole, Qt::Unchecked);
                items.append(listitem);
                values.clear();
            }
            selectdlg.ImportProfileListView->insertTopLevelItems(0, items);
        }
        bool ret = selectdlg.exec();

        if (ret == true) {
            QTreeWidgetItemIterator it2(selectdlg.ImportProfileListView);
            while (*it2) {
                VpnAccountData *data = NULL;
                it = 0;
                for (int accountIdx = 0; accountIdx < ImportedAccountList->size(); ++accountIdx) {
                    it = ImportedAccountList->at(accountIdx);
                    if (it->getName() == (*it2)->text(0) && (*it2)->data(0, Qt::CheckStateRole).toInt() == Qt::Checked) {
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n("Profile marked for import: %1", it->getName()) , KVpncEnum::debug);
                        data = it;
                        importCount++;
                        RetName = it->getName();
                        AccountList->append(data);
						saveOptions(true, data->getName());
                        break;
                    }
                }
                *it2++;
            }
            if (selectdlg.OpenProfileManagerCheckBox->isChecked() && !ImportedAccountList->isEmpty())
                openProfileManager = true;
        } else {
            KMessageBox::sorry(0, i18n("Import canceled."));
            return false;
        }


        QString msg = "";
        if (importCount > 0)
            msg = i18n("Import was successful. %1 profiles are imported.", QString::number(importCount));
        else
            msg = i18n("Import was canceled because no profiles are selected.", QString::number(importCount));

        KMessageBox::information(0, msg, i18n("Import success"));

    } else {
        KMessageBox::error(0, i18n("Failed to read \"%1\"." ,   filename));
        return false;
    }


    return true;

}

bool KVpncConfig::importFritzboxConfig(QString filename, QString& RetName, bool& openProfileManager)
{
    /*
    // example of vpn config fritzbox user
    version = {
    	revision = "$Revision: 1.30 $";
    	creatversion = "1.1";
    }


    pwcheck = {
    }


    datapipecfg = {
    	security = dpsec_quiet;
    	icmp = {
    		ignore_echo_requests = no;
    		destunreach_rate = {
    			burstfactor = 6;
    			timeout = 1;
    }
    timeexceeded_rate = {
    	burstfactor = 6;
    	timeout = 1;
    }
    echoreply_rate = {
    	burstfactor = 6;
    	timeout = 1;
    }
    }
    masqtimeouts = {
    	tcp = 15m;
    	tcp_fin = 2m;
    	tcp_rst = 3s;
    	udp = 5m;
    	icmp = 30s;
    	got_icmp_error = 15s;
    	any = 5m;
    	tcp_connect = 6m;
    	tcp_listen = 2m;
    }
    ipfwlow = {
    	input = {
    }
    output = {
    }
    }
    ipfwhigh = {
    	input = {
    }
    output = {
    }
    }
    NAT_T_keepalive_interval = 20;
    }


    targets = {
    	policies = {
    		name = "My Fritzbox";
    		connect_on_channelup = no;
    		always_renew = no;
    		reject_not_encrypted = no;
    		dont_filter_netbios = yes;
    		localip = 0.0.0.0;
    		virtualip = 192.168.178.201;
    		remoteip = 0.0.0.0;
    		remotehostname = "dnyn.myfb.com";
    		localid = {
    			user_fqdn = "user@domain.com";
    }
    mode = mode_aggressive;
    phase1ss = "all/all/all";
    keytype = keytype_pre_shared;
    key = "geheim";
    cert_do_server_auth = no;
    use_nat_t = yes;
    use_xauth = no;
    use_cfgmode = no;
    phase2localid = {
    	ipaddr = 192.168.178.201;
    }
    phase2remoteid = {
    	ipnet = {
    		ipaddr = 192.168.178.0;
    		mask = 255.255.255.0;
    }
    }
    phase2ss = "esp-all-all/ah-none/comp-all/pfs";
    accesslist = "permit ip any 192.168.178.0 255.255.255.0";
    wakeupremote = no;
    }
    }


    policybindings = {
    }

    */
    QFile importfile (filename);
    if (!importfile.exists()) {
        KMessageBox::error ( 0, i18n ( "Reading of \"%1\" has been failed!", filename ) );
        return false;
    }
    if ( importfile.open(IO_ReadOnly)) {
        QString line = NULL;
        VpnAccountData *profiledata = new VpnAccountData(VpnAccountData::racoon,"fritzbox") ;
        QTextStream stream(&importfile);
        bool datapipecfgFound = false;
        bool policiesFound = false;
        bool targetsFound = false;
        bool localidFound = false;
        bool phase2localidFound = false;
        bool phase2remoteidFound = false;
        bool ipnetFound = false;
        bool nameFound = false;

        profiledata->setDescription(QString(i18n("import from ")+filename));
        profiledata->setConnectionType( VpnAccountData::racoon);
        profiledata->setUsePerfectForwardSecrety(true);
        profiledata->setPerfectForwardSecrety("modp1024");
        profiledata->setUseIkeGroup(true);
        profiledata->setIkeGroup("modp1024");
        profiledata->setIpsecIke("aes");
        profiledata->setHashAlgo( "sha1");
        profiledata->setUseAuthenticationAlgorithm(true);
        profiledata->setEncryptionAlgorithm( "aes");
        profiledata->setAuthenticationAlgorithm( "hmac_sha1" );
        profiledata->setLocalIDType("user_fqdn");
        profiledata->setReplaceDefaultRoute(false);
        profiledata->setNetworkDevice("default");
        profiledata->setUseDnsUpdate(false);


        while ( !stream.atEnd() ) {
            line = removeWhiteSpaceAtBegin(stream.readLine()).simplified();
            if (KvpncDebugLevel > 6)
                appendLogEntry(i18n ("import fritzbox config: line: %1", line), KVpncEnum::debug);

            if (line.startsWith("datapipecfg")) {
                datapipecfgFound = true;
                if (KvpncDebugLevel > 2)
                    appendLogEntry(i18n ("import fritzbox config: %1 found", QString("datapipecfg")), KVpncEnum::debug);
            }
            if (line.startsWith("policies")) {
                policiesFound = true;
                if (KvpncDebugLevel > 2)
                    appendLogEntry(i18n ("import fritzbox config: %1 found", QString("policies")), KVpncEnum::debug);
            }
            if (line.startsWith("targets")) {
                targetsFound = true;
                if (KvpncDebugLevel > 2)
                    appendLogEntry(i18n ("import fritzbox config: %1 found", QString("targets")), KVpncEnum::debug);
            }
            if (line.startsWith("localid")) {
                localidFound = true;
                if (KvpncDebugLevel > 2)
                    appendLogEntry(i18n ("import fritzbox config: %1 found", QString("localid")), KVpncEnum::debug);
            }
            if (line.startsWith("phase2localid")) {
                phase2localidFound = true;
                if (KvpncDebugLevel > 2)
                    appendLogEntry(i18n ("import fritzbox config: %1 found", QString("phase2localid")), KVpncEnum::debug);
            }
            if (line.startsWith("phase2remoteid")) {
                phase2remoteidFound = true;
                if (KvpncDebugLevel > 2)
                    appendLogEntry(i18n ("import fritzbox config: %1 found", QString("phase2remoteid")), KVpncEnum::debug);
            }
            if (line.startsWith("ipnet")) {
                ipnetFound = true;
                if (KvpncDebugLevel > 2)
                    appendLogEntry(i18n ("import fritzbox config: ipnetFound found"), KVpncEnum::debug);
            }
            if ( datapipecfgFound ) {
                // here we can read masq timeouts, and so on.
            }
            if (targetsFound && policiesFound ) {
                if (line.startsWith("name = ")) {
                    QString ProfileName=line.section("= ",1,1).replace("\"","").replace(";","").replace(" ","_");
                    if (KvpncDebugLevel > 2)
                        appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("name"), ProfileName), KVpncEnum::debug);
                    profiledata->setName(ProfileName);
                    nameFound = true;
                }
                if (line.startsWith(" always_renew = ")) {
                    bool reconnectAfterConnectionLost=false;
                    if (line.section("= ",1,1).replace(";","") == "yes")
                        reconnectAfterConnectionLost = true;
                    if (KvpncDebugLevel > 2) {
                        if (reconnectAfterConnectionLost)
                            appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("always_renew"), i18n("yes")), KVpncEnum::debug);
                        else
                            appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("always_renew"), i18n("no")), KVpncEnum::debug);
					}
                    profiledata->setDoReconnectAfterConnectionLost(reconnectAfterConnectionLost);
                }
                if (line.startsWith("dont_filter_netbios = ")) {
                    bool dont_filter_netbios=false;
                    if (line.section("= ",1,1).replace(";","") == "yes")
                        dont_filter_netbios = true;
                    if (KvpncDebugLevel > 2) {
                        if (dont_filter_netbios)
                            appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("dont_filter_netbios"), i18n("yes")), KVpncEnum::debug);
                        else
                            appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("dont_filter_netbios"), i18n("no")), KVpncEnum::debug);
					}
                    // nothing to yet
                }
                if (line.startsWith("localip = ")) {
                    QString LocalIp=line.section("= ",1,1).replace("\"","").replace(";","");
                    if (KvpncDebugLevel > 2)
                        appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("localip"), LocalIp), KVpncEnum::debug);
                    // nothing to do yet
                }
                if (line.startsWith("virtualip = ")) {
                    QString LocalVirtualIp=line.section("= ",1,1).replace("\"","").replace(";","");
                    if (KvpncDebugLevel > 2)
                        appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("virtualip"), LocalVirtualIp), KVpncEnum::debug);
                    profiledata->setUseLeftSourceIp(true);
                    profiledata->setLeftSourceIp(LocalVirtualIp);
                }
                if (line.startsWith("remoteip = ")) {
                    QString RemoteIp=line.section("= ",1,1).replace("\"","").replace(";","");
                    if (KvpncDebugLevel > 2)
                        appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("remoteip"), RemoteIp), KVpncEnum::debug);
                    // nothing to do yet
                }
                if (line.startsWith("remotehostname = ")) {
                    QString Gateway=line.section("= ",1,1).replace("\"","").replace(";","");
                    if (KvpncDebugLevel > 2)
                        appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("remotehostname"), Gateway), KVpncEnum::debug);
                    profiledata->setGateway(Gateway);
                }
                if (localidFound) {
                    if (line.startsWith("user_fqdn = "))
                    {
                        QString LocalId=line.section("= ",1,1).replace("\"","").replace(";","");
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("user_fqdn")+" ("+i18n("local id")+")", LocalId), KVpncEnum::debug);
                        profiledata->setSpecialLocalID(LocalId);
                        profiledata->setUseSpecialLocalID(true);
						profiledata->setLocalIDType("user_fqdn");
                        localidFound = false;
                    }
                }
                if (line.startsWith("mode = ")) {
                    QString IpsecExchangeMode=line.section("= ",1,1).replace(";","");

                    if (KvpncDebugLevel > 2)
                        appendLogEntry(i18n ("import fritzbox config: %1 found: %2", i18n("exchange mode"), IpsecExchangeMode), KVpncEnum::debug);

                    if (IpsecExchangeMode == "mode_aggressive")
                        profiledata->setExchangeMode("aggressive");
                    else
                        profiledata->setExchangeMode("main");
                }
                if (line.startsWith("keytype = ")) {
                    QString AuthType=line.section("= ",1,1).replace(";","");
                    if (KvpncDebugLevel > 2)
                        appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("keytype"), AuthType), KVpncEnum::debug);

                    if (AuthType == "keytype_pre_shared")
                        profiledata->setAuthType(VpnAccountData::psk);
                    else
                        profiledata->setAuthType(VpnAccountData::cert);
                }
                if (line.startsWith("key = ")) {
                    QString PreshardKey=line.section("= ",1,1).replace("\"","").replace(";","");
                    if (KvpncDebugLevel > 2 && KvpncDebugLevel < 5)
                        appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("key"), "******"), KVpncEnum::debug);
                    if (KvpncDebugLevel > 5)
                        appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("key"), PreshardKey), KVpncEnum::debug);
                    profiledata->setPreSharedKey(PreshardKey);
                    profiledata->setPskIsInFile(false);
                }
                if (line.startsWith("cert_do_server_auth = ")) {
                    bool cert_do_server_auth=false;
                    if (line.section("= ",1,1).replace(";","") == "yes")
                        cert_do_server_auth = true;
                    if (KvpncDebugLevel > 2) {
                        if (cert_do_server_auth)
                            appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("cert_do_server_auth"), i18n("yes")), KVpncEnum::debug);
                        else
                            appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("cert_do_server_auth"), i18n("no")), KVpncEnum::debug);
					}
                    // nothing to to yet
                }
                if (line.startsWith("use_nat_t = ")) {
                    bool UseNat=false;
                    if (line.section("= ",1,1).replace(";","") == "yes")
                        UseNat = true;
                    if (KvpncDebugLevel > 2) {
                        if (UseNat)
                            appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("use_nat_t"), i18n("yes")), KVpncEnum::debug);
                        else
                            appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("use_nat_t"), i18n("no")), KVpncEnum::debug);
					}
                    profiledata->setUseNat(UseNat);
                    profiledata->setUseUdp(true);
                }
                if (line.startsWith("use_xauth = ")) {
                    bool UseXauth=false;
                    if (line.section("= ",1,1).replace(";","") == "yes")
                        UseXauth = true;
                    if (KvpncDebugLevel > 2) {
                        if (UseXauth)
                            appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("use_xauth"), i18n("yes")), KVpncEnum::debug);
                        else
                            appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("use_xauth"), i18n("no")), KVpncEnum::debug);
					}
                    profiledata->setAuthWithUsernameAndPassword(UseXauth);
                }
                if (line.startsWith("use_cfgmode = ")) {
                    bool ModeConfig=false;
                    if (line.section("= ",1,1).replace(";","") == "yes")
                        ModeConfig = true;
                    if (KvpncDebugLevel > 2) {
                        if (ModeConfig)
                            appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("use_cfgmode"), i18n("yes")), KVpncEnum::debug);
                        else
                            appendLogEntry(i18n ("import fritzbox config: %1 found: %2", QString("use_cfgmode"), i18n("no")), KVpncEnum::debug);
					}
                    profiledata->setUseModeConfig(ModeConfig);
                }
                if (phase2localidFound) {
                    if (line.startsWith("ipaddr = ")) {
                        QString Phase2LocalId=line.section("= ",1,1).replace("\"","").replace(";","");
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n ("import fritzbox config: %1 found: %2", i18n("ip addr for phase 2"), Phase2LocalId), KVpncEnum::debug);
                        // nothing to do yet
                    }
                }
                if (phase2remoteidFound && ipnetFound) {
                    profiledata->setUseRemoteNetwork(true);
                    if (line.startsWith("ipaddr = ")) {
                        QString RemoteNetWorkAddr=line.section("= ",1,1).replace(";","");
                        if (KvpncDebugLevel > 2)
                            appendLogEntry(i18n ("import fritzbox config: %1 found: %2", i18n("remote network ip"), RemoteNetWorkAddr), KVpncEnum::debug);
                        profiledata->setRemoteNetAddr(RemoteNetWorkAddr);
                    }
                    if (line.startsWith("mask = ")) {
                        QString RemoteNetWorkMask=line.section("= ",1,1).replace(";","");
                        QString RemoteNetWorkMaskNumeric = QString().setNum(Utils(this).dottedIpv4Netmask2NetmaskBytes(RemoteNetWorkMask));
                        if (KvpncDebugLevel > 2) {
                            appendLogEntry(i18n ("import fritzbox config: %1 found: %2", i18n("remote network netmask"), RemoteNetWorkMask), KVpncEnum::debug);

                            appendLogEntry(i18n("Netmask (dotted): %1, numeric value: %2", RemoteNetWorkMask, RemoteNetWorkMaskNumeric), KVpncEnum::debug);
                        }
                        profiledata->setRemoteNetMask(RemoteNetWorkMaskNumeric);
                    }
                }
            }
        }
        if (policiesFound && nameFound) {
            bool ok = false;
            VpnAccountData * it;
            bool nameOk = false;
            while ( nameOk == false ) {
                for (int accountIdx = 0; accountIdx < AccountList->size(); ++accountIdx) {
                    it = AccountList->at(accountIdx);
                    if ( it->getName() == profiledata->getName() ) {
                        //account->setName( QString( account->getName() + "_2" ) );
                        // 				KMessageBox::information ( this, i18n( "Profile name exists!\n It will be renamed to \"%1\".", account->getName() ), i18n( "Name exist, renamed" ) );
                        KMessageBox::error ( 0, i18n ( "Profile name exists!" ), i18n ( "Name Exists" ) );
                        QString newName = KInputDialog::getText ( i18n ( "New Name" ), i18n ( "New name for profile:" ), QString ( profiledata->getName() + "_2" ), &ok );
                        if (newName.isEmpty())
                        {
                            KMessageBox::information ( 0, i18n ( "Import was canceled." ) );
                            appendLogEntry ( i18n ( "Import was canceled." ), KVpncEnum::info );
                            return false;
                        }
                        if (newName != it->getName() )
                        {
                            profiledata->setName ( newName );
                            nameOk = true;
                        }

                    }
                    nameOk = true;
                }
                nameOk = true;
            }

            if ( nameOk == true ) {
                AccountList->append ( profiledata );
                RetName = profiledata->getName();
                saveOptions(true, RetName);

                appendLogEntry ( i18n ( "Import of \"%1\" (%2) was successful.", profiledata->getName(), QString("Fritzbox") ), KVpncEnum::info );

                QString bin = "racoon";
                //std::cout << "Tool (bin): " << bin << std::endl;
                if ( !ToolList->isEmpty() ) {
                    for (int toolIdx = 0; toolIdx < ToolList->size(); ++toolIdx) {
                        ToolInfo *tool = ToolList->at(toolIdx);
                        if ( bin == tool->Name ) {
                            if ( tool->PathToExec.section ( '/', -1 ) != bin ) {
                                // program is NOT installed
                                KMessageBox::information ( 0, i18n ( "The required tool (%1) is not installed, please install it before you are connecting and restart kvpnc.", bin ), i18n ( "Tool Missing" ) );
                            }
                            break;
                        }
                    }
                }
            } else {
                KMessageBox::information ( 0, i18n ( "Import was canceled." ) );
                appendLogEntry ( i18n ( "Import was canceled." ), KVpncEnum::info );
                return false;
            }
        }
        QString msg="";
        if (policiesFound && nameFound)
            msg = i18n("Import was successful. 1 profile was imported.");
        else
            msg = i18n("Import was canceled because no profile was found.");

        KMessageBox::information ( 0, msg,i18n("Import success") );
        return policiesFound && nameFound;
    }
    else {
        KMessageBox::error ( 0, i18n ( "Reading of \"%1\" has been failed!", filename ) );
        return false;
    }
    return true;

}

VpnAccountData* KVpncConfig::findProfile(QList<VpnAccountData *> *list, const QString& Name)
{
    VpnAccountData *it = 0L;
    bool found = false;
    if (!list->isEmpty()) {
        for (int accountIdx = 0; accountIdx < AccountList->size(); ++accountIdx) {
            it = AccountList->at(accountIdx);
            if (Name == it->getName()) {
                found = true;
                break;
            }
        }
    }
    if (found)
        return it;
    else {
        return NULL;
    }
}

QString KVpncConfig::removeWhiteSpaceAtBegin(const QString str)
{
    QString newstr = "";
    int i = 0;
    for (i = 0;i < (int) str.length();i++) {
        if (!QChar(str.at(i)).isSpace())
            break;
    }
    newstr = str.right(str.length() - i);
    return newstr;
}

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(QIODevice::ReadOnly)) {
        if (backupOriginalConfFile.open(QIODevice::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(QIODevice::ReadOnly)) {
        if (backupOriginalConfFile.open(QIODevice::WriteOnly)) {
            QString OriginalConfFileContent = QString(OriginalConfFile.readAll()) ;
            writestream << OriginalConfFileContent;
            OriginalConfFile.close();
            backupOriginalConfFile.close();
        }
    }
}

void KVpncConfig::getToolsInfo()
{
    if (!ToolList->isEmpty()) {
        for (int toolIdx = 0; toolIdx < ToolList->size(); ++toolIdx) {
            ToolInfo *tool = ToolList->at(toolIdx);
            tool->collectToolInfo();
        }
    }
}

void KVpncConfig::removeEntry(QString Name)
{
    KStandardDirs * dirs = KGlobal::dirs();
    QString filePath = dirs->findResource("config", "kvpncrc");
    KConfigGroup configgroup = KGlobal::config()->group("Notification Messages");
    appPointer->processEvents();

    if (useKwallet && KWallet::Wallet::isEnabled())
        configgroup.deleteEntry("First use of Kwallet", false);


    /* = user data = */
    VpnAccountData *it = 0L;
    if (!AccountList->isEmpty()) {
        for (int accountIdx = 0; accountIdx < AccountList->size(); ++accountIdx) {
            it = AccountList->at(accountIdx);
            if (!it->getName().isEmpty()) {
                QString name = it->getName();
                if (it->getName() == Name) {
                    QString ProfileName = "Profile_";
                    ProfileName += name;
                    KConfigGroup configgroup = KGlobal::config()->group(ProfileName);

                    /* passwords with kwallet */
                    if (useKwallet && KWallet::Wallet::isEnabled()) {
                        if (KvpncDebugLevel > 4)
                            appendLogEntry(i18n("Wallet enabled and available, writing to wallet."), KVpncEnum::debug);
                        // Open local wallet
                        wallet = KWallet::Wallet::openWallet(KWallet::Wallet::LocalWallet(), KWallet::Wallet::Synchronous);
                        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);
                                int UserPasswordOK = wallet->removeEntry(QString(Name + "__user_pw"));
                                int PskOK = wallet->removeEntry(QString(Name + "__psk"));
                                int PskKeyPassOK = wallet->removeEntry(QString(Name + "__priv_key_pwd"));
//         wallet->sync();

                                if (KvpncDebugLevel > 2) {
                                    if (UserPasswordOK)
                                        appendLogEntry(i18n("Deleting %1 succeeded." , i18n("user password")), KVpncEnum::debug);
                                    else
                                        appendLogEntry(i18n("Deleting %1 failed." , i18n("user password")), KVpncEnum::debug);
                                    //
                                    if (PskOK)
                                        appendLogEntry(i18n("Deleting %1 succeeded." , i18n("preshared key")), KVpncEnum::debug);
                                    else
                                        appendLogEntry(i18n("Deleting %1 failed." , i18n("preshared key")), KVpncEnum::debug);

                                    if (PskKeyPassOK)
                                        appendLogEntry(i18n("Deleting %1 succeeded." , i18n("private key password")), KVpncEnum::debug);
                                    else
                                        appendLogEntry(i18n("Deleting %1 failed." , i18n("private key password")), KVpncEnum::debug);
                                }
                            } else {
                                KMessageBox::error(0, i18n("Unable to create wallet folder for kvpnc."));
                                appendLogEntry(i18n("Unable to create wallet folder for kvpnc."), KVpncEnum::error);
                            }
                        }
                    } else {
                        if (KvpncDebugLevel > 0)
                            appendLogEntry(i18n("Wallet disabled or not available, writing to config file."), KVpncEnum::debug);
                        // write passwords to config file :|
//        configgroup.deleteEntry("User password");
//        configgroup.deleteEntry("Pre shared key");
//        configgroup.deleteEntry("PrivateKey password");
                    }
//      configgroup.deleteEntry("User password");
//      configgroup.deleteEntry("Pre shared key");
//      configgroup.deleteEntry("PrivateKey password");
//
//                     configgroup.deleteEntry("Connection type");
//                     configgroup.deleteEntry("VPN Gateway");
//                     configgroup.deleteEntry("VPN ID");
//                     configgroup.deleteEntry("Username");
//                     configgroup.deleteEntry("Save user password");
//                     configgroup.deleteEntry("Save PSK");
//                     configgroup.deleteEntry("Private key");
//                     configgroup.deleteEntry("Use advanced settings");
//                     configgroup.deleteEntry("Application version");
//                     configgroup.deleteEntry("Local port");
//                     configgroup.deleteEntry("NT domain name");
//                     configgroup.deleteEntry("Perfect forward secrety");
//                     configgroup.deleteEntry("IKE group");
//                     configgroup.deleteEntry("Use application version");
//                     configgroup.deleteEntry("Use global IPSec secret");
//                     configgroup.deleteEntry("Use IKE group");
//                     configgroup.deleteEntry("Use local port");
//                     configgroup.deleteEntry("Use NT domain name");
//                     configgroup.deleteEntry("Use single DES");
//                     configgroup.deleteEntry("Use perfect Forward Secrety");
//                     configgroup.deleteEntry("Remote net address");
//                     configgroup.deleteEntry("Remote net mask");
//                     configgroup.deleteEntry("x509 certificate");
//                     configgroup.deleteEntry("Ca certificate");
//                     configgroup.deleteEntry("Network device");
//                     configgroup.deleteEntry("Cert path");
//                     configgroup.deleteEntry("Auth type");
//                     configgroup.deleteEntry("do ping ip");
//                     configgroup.deleteEntry("Ping host IP");
//                     configgroup.deleteEntry("Use special remote ID");
//                     configgroup.deleteEntry("Special server certificate");
//                     configgroup.deleteEntry("Use special server certificate");
//                     configgroup.deleteEntry("Special remote ID");
//                     configgroup.deleteEntry("Use UDP-protocol");
//                     configgroup.deleteEntry("Use UDP-port");
//                     configgroup.deleteEntry("local UDP port");
//                     configgroup.deleteEntry("use DNS_UPDATE");
//                     configgroup.deleteEntry("use DNS-server");
//                     configgroup.deleteEntry("DNS server");
//                     configgroup.deleteEntry("get dns server from peer");
//                     configgroup.deleteEntry("refuse 40 bit encryption");
//
//                     appPointer->processEvents();
//
//                     configgroup.deleteEntry("refuse 128 bit encryption");
//                     configgroup.deleteEntry("require stateless encryption");
//                     configgroup.deleteEntry("require mppe");
//                     configgroup.deleteEntry("Disable MPPE compression");
//                     configgroup.deleteEntry("Local virtual IP");
//                     configgroup.deleteEntry("Remote virtual IP");
//                     configgroup.deleteEntry("Pre shared key file");
//                     configgroup.deleteEntry("Execute command before connect");
//                     configgroup.deleteEntry("Execute command after connect");
//                     configgroup.deleteEntry("Execute command before disconnect");
//                     configgroup.deleteEntry("Execute command after disconnect");
//                     configgroup.deleteEntry("Command before connect");
//                     configgroup.deleteEntry("Command after connect");
//                     configgroup.deleteEntry("Command before disconnect");
//                     configgroup.deleteEntry("Command after disconnect");
//                     configgroup.deleteEntry("Use no BSD compression");
//                     configgroup.deleteEntry("Use no deflate");
//                     configgroup.deleteEntry("Set default route");
//                     configgroup.deleteEntry("Replace default route");
//                     configgroup.deleteEntry("Use own MTU");
//                     configgroup.deleteEntry("Use own MRU");
//                     configgroup.deleteEntry("MTU for pppd");
//                     configgroup.deleteEntry("MRU for pppd");
//                     configgroup.deleteEntry("Use Virtual IP");
//                     configgroup.deleteEntry("Virtual IP");
//                     configgroup.deleteEntry("PSK is in file");
//                     configgroup.deleteEntry("Use additional network routes");
//                     configgroup.deleteEntry("Hash algorithm");
//                     configgroup.deleteEntry("Tunnel device type");
//                     configgroup.deleteEntry("Use userdefined port");
//                     configgroup.deleteEntry("Userdefined port");
//                     configgroup.deleteEntry("Keep default route");
//                     configgroup.deleteEntry("Additional network routes");
//                     configgroup.deleteEntry("AuthWithUsernameAndPassword");
//                     configgroup.deleteEntry("AllowEmptyGroupPassword");
//                     configgroup.deleteEntry("Encryption algorithm");
//                     configgroup.deleteEntry("Authentication algorithm");

                    configgroup.deleteGroup(ProfileName);
                    KGlobal::config()->deleteGroup(ProfileName);

                    /* give info */
                    //slotStatusMsg ( i18n( "Profile \"%1\" removed." , QString(Name )), ID_FLASH_MSG );
                    appendLogEntry(i18n("Profile \"%1\" removed." ,  Name) , KVpncEnum::info);
                    AccountList->removeAll(it);
                    break;
                }
            }
        }
        appPointer->processEvents();
    }
    configgroup.sync();
    appPointer->processEvents();
}

#include "kvpncconfig.moc"
