/*****************************************************************************
 * Copyright (C) 2004-2009 Christoph Thielecke <crissi99@gmx.de>             *
 * Peter Simonsson <psn@linux.se> (contains some code from klcc)             *
 * Stefan Hundhammer <sh@suse.de> (contains some code from kdirstat)         *
 *                                                                           *
 * 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 "kvpnc.h"

#include <QTextStream>
#include <QtCore/QDateTime>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QRegExp>
#include <QtCore/QStringList>
#include <QtCore/QTimer>
#include <QtCore/QByteArray>
#include <QtGui/QCheckBox>
#include <QtGui/QCloseEvent>
#include <QtGui/QColor>
#include <QtGui/QComboBox>
#include <QtGui/QCursor>
#include <QtGui/QDesktopServices>
#include <QtGui/QLabel>
#include <QtGui/QPixmap>
#include <QtGui/QPushButton>
#include <QtGui/QSpinBox>
#include <QtGui/QStatusBar>
#include <QtGui/QToolTip>
#include <QtGui/QMenu>

#include <kaboutdata.h>
#include <kaction.h>
#include <kactioncollection.h>
#include <kapplication.h>
#include <kcombobox.h>
#include <kconfiggroup.h>
#include <kdebug.h>
#include <kedittoolbar.h>
#include <kfiledialog.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <kinputdialog.h>
#include <kio/netaccess.h>
#include <klineedit.h>
#include <klocale.h>
#include <kmainwindow.h>
#include <kmessagebox.h>
#include <knotification.h>
#include <knotifyconfigwidget.h>
#include <knuminput.h>
#include <kpassworddialog.h>
#include <krun.h>
#include <kstandardaction.h>
#include <kstandarddirs.h>
#include <kstatusbar.h>
#include <ktemporaryfile.h>
#include <ktoolbar.h>
#include <kurlrequester.h>
#include <kwallet.h>

#include <cstdlib>
#include <ctime>
#include <iomanip>

#include "ui_mainviewbase4.h"
#include "ciscocertificateenrollment.h"
#include "debugoutputtextedit.h"
#include "enterpassworddialog.h"
#include "enterxauthinteractivepasscodedialog.h"
#include "generateopenvpnkeydialog.h"
#include "helpdialog.h"
#include "importcertificatedialog.h"
#include "importopenvpnprofiledialog.h"
#include "importprofiledialog.h"
#include "logviewerdialog.h"
#include "mainview.h"
#include "manageciscocert.h"
#include "networkinterface.h"
#include "newprofiledialog.h"
#include "newprofilewizard.h"
#include "toolsinfodialog.h"
#include "utils.h"
#include "vpnaccountdata.h"
#include "vpntypesinfodialog.h"

KVpnc::KVpnc(KApplication *parent, QWidget*)
{
    QDBusConnection::sessionBus().registerObject("/kvpnc", this, QDBusConnection::ExportScriptableSlots);

    this->parent = parent;
    setCaption(i18n("KVpnc"));

    GlobalConfig = new KVpncConfig(this, statusBar());
    GlobalConfig->appPointer = parent;
    GlobalConfig->config = KGlobal::config().data();

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

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

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

    TunnelInterfaceIP = "";
    VpncDevice = "";
    L2tpPppDevice = "";
    PppdDevice = "";
    OpenvpnDevice = "";
    SshDevice = "";

    connectCounter = 0;

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

    AuthRetry = false;
    GlobalConfig->doAutoConnectAtStartup = false;
    quitFromKicker = false;
    ciscoVpncRunning = false;
    showProfilesOnly = false;

    pppdCapabilitiesCollected = false;

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

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

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

    KConfigGroup configgroup = KGlobal::config()->group("ToolBar Settings");
    toolBar("mainToolBar") ->applySettings(configgroup);
    //  ShowToolbarAction->setChecked( GlobalConfig->showToolBar );

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

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


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

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

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

    QuickConnectMenu = new QMenu(KVpncDock->menu());
    connect(QuickConnectMenu, SIGNAL(triggered(QAction *)), this, SLOT(doQuickConnect(QAction *)));

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

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

    for (int SessionIdx = 0; SessionIdx < GlobalConfig->AccountList->count(); SessionIdx++) {
        QuickConnectMenu->addAction(GlobalConfig->AccountList->at(SessionIdx) ->getName());
        mw->SessionCombo->insertItem(SessionIdx, GlobalConfig->AccountList->at(SessionIdx) ->getName());
    }
    mw->SessionCombo->model()->sort(0);

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

    KAction ConnectToAction(this);
    QuickConnectMenu->setTitle(i18n("Connecting To..."));
    KVpncDock->menu()->addMenu(QuickConnectMenu);
    KVpncDock->menu()->insertSeparator(&ConnectToAction);

    if (!GlobalConfig->lastProfile.isEmpty()) {
        VpnAccountData * it = 0L;
        for (int SessionIdx = 0; SessionIdx < GlobalConfig->AccountList->count(); SessionIdx++) {
            if (QString(GlobalConfig->AccountList->at(SessionIdx)->getName()) == GlobalConfig->lastProfile) {
                if (GlobalConfig->KvpncDebugLevel > 2)
                    GlobalConfig->appendLogEntry(i18n("Last-used profile found: %1" , GlobalConfig->lastProfile), KVpncEnum::debug);
                GlobalConfig->currentProfile = it;
                mw->SessionCombo->setCurrentItem(GlobalConfig->lastProfile);
                sessionToggled(GlobalConfig->lastProfile);
                break;
            }
        }
    } else {
        if (GlobalConfig->KvpncDebugLevel > 2)
            GlobalConfig->appendLogEntry(i18n("No last-used profile found."), KVpncEnum::info);
        if (!GlobalConfig->AccountList->isEmpty()) {
            this->ConnectAction->setEnabled(true);
            this->mw->buttonConnect->setEnabled(true);
            mw->SessionCombo->setCurrentIndex(0);
            GlobalConfig->currentProfile = GlobalConfig->AccountList->first();
            mw->SessionCombo->setEnabled(true);
        } else {
            DeleteSessionAction->setEnabled(false);
            ConnectAction->setEnabled(false);
            GlobalConfig->currentProfile = 0L;
        }
    }

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

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

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

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

}

KVpnc::~KVpnc()
{
    delete env;
    delete QuickConnectMenu;
    delete GlobalConfig;
    delete SaveSessionAction;
    delete DeleteSessionAction;
    delete ImportSessionAction;
    delete ImportOpenvpnProfileAction;
    delete ImportCertAction;
    delete ConnectAction;
    delete DisconnectAction;
    delete ProfileManagerAction;
    delete NewProfileWizardAction;
    delete DonateAction;
    delete VisitHomepageAction;
    delete DebugconsoleAction;
    delete ToolsInfoAction;
    delete LogViewerAction;
    delete GenerateOpenvpnKeyAction;
    delete ManageCiscoCertAction;
    delete CiscoCertEnrollmentAction;
}

void KVpnc::initAction()
{
    setWindowIcon(KIcon("disconnected"));

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

    SaveSessionAction = new KAction(this);
    SaveSessionAction->setText(i18n("&Save Profile..."));
    SaveSessionAction->setIcon(KIcon("save-document"));
    SaveSessionAction->setShortcut(Qt::Key_S);
    actionCollection()->addAction("saveSession", SaveSessionAction);
    connect(SaveSessionAction, SIGNAL(triggered()), SLOT(saveSessionClicked()));

    DeleteSessionAction = new KAction(KIcon("edit-delete"), i18n("&Delete Profile..."), actionCollection());
    DeleteSessionAction->setShortcut(Qt::Key_D);
    actionCollection()->addAction("deleteSession", DeleteSessionAction);
    connect(DeleteSessionAction, SIGNAL(triggered()), SLOT(deleteSessionClicked()));

    RenameSessionAction = new KAction(this);
    RenameSessionAction->setText(i18n("&Rename Profile..."));
    RenameSessionAction->setIcon(KIcon("edit-rename"));
    RenameSessionAction->setShortcut(Qt::Key_D);
    actionCollection()->addAction("renameSession", RenameSessionAction);
    connect(RenameSessionAction, SIGNAL(triggered()), SLOT(renameSessionClicked()));

    ImportSessionAction = new KAction(KIcon("cisco"), i18n("&Import Cisco pcf file..."), actionCollection());
    ImportSessionAction->setShortcut(Qt::Key_F);
    actionCollection()->addAction("importSession", ImportSessionAction);
    connect(ImportSessionAction, SIGNAL(triggered()), SLOT(importProfileClicked()));

    ImportOpenvpnProfileAction = new KAction(KIcon("openvpnimport"), i18n("Import &OpenVPN config file..."), actionCollection());
    ImportOpenvpnProfileAction->setShortcut(Qt::Key_O);
    actionCollection()->addAction("importOpenvpnConfig", ImportOpenvpnProfileAction);
    connect(ImportOpenvpnProfileAction, SIGNAL(triggered()), SLOT(importOpenvpnProfileClicked()));

    ImportFreeswanProfileAction = new KAction(KIcon("openswan"), i18n("Import &Freeswan/Openswan/strongSwan config file..."), actionCollection());
    ImportFreeswanProfileAction->setShortcut(Qt::Key_I);
    actionCollection()->addAction("importFreeswanConfig", ImportFreeswanProfileAction);
    connect(ImportFreeswanProfileAction, SIGNAL(triggered()), SLOT(importIpsecProfileClicked()));

    ImportFritzboxProfileAction = new KAction(KIcon("fritzboximport"), i18n("Import Fritz&box VPN user config file..."), actionCollection());
    ImportFritzboxProfileAction->setShortcut(Qt::Key_F);
    actionCollection()->addAction("importFritzboxConfig", ImportFritzboxProfileAction);
    connect(ImportFritzboxProfileAction, SIGNAL(triggered()), SLOT(importFritzboxProfileClicked()));

    ImportCertAction = new KAction(KIcon("certimport"), i18n("Import &certificate..."), actionCollection());
    ImportCertAction->setShortcut(Qt::Key_C);
    actionCollection()->addAction("importCert", ImportCertAction);
    connect(ImportCertAction, SIGNAL(triggered()), SLOT(importCertClicked()));


    ManageCiscoCertAction = new KAction(KIcon("certimport"), i18n("Manage Cisco certificates..."), actionCollection());
    ManageCiscoCertAction->setShortcut(Qt::Key_C);
    actionCollection()->addAction("manageCiscoCert", ManageCiscoCertAction);
    connect(ManageCiscoCertAction, SIGNAL(triggered()), SLOT(manageCiscoCertClicked()));

    CiscoCertEnrollmentAction = new KAction(KIcon("certimport"), i18n("Enroll Cisco certificates..."), actionCollection());
    CiscoCertEnrollmentAction->setShortcut(Qt::Key_T);
    actionCollection()->addAction("enrollCiscoCert", CiscoCertEnrollmentAction);
    connect(CiscoCertEnrollmentAction, SIGNAL(triggered()), SLOT(enrollCiscoCertClicked()));

    ExportOpenvpnProfileAction = new KAction(KIcon("arrow-up-double"), i18n("Export &OpenVPN profile to config file"), actionCollection());
    ExportOpenvpnProfileAction->setShortcut(Qt::Key_O);
    actionCollection()->addAction("exportOpenvpnConfig", ExportOpenvpnProfileAction);
    connect(ExportOpenvpnProfileAction, SIGNAL(triggered()), SLOT(exportOpenvpnProfileClicked()));

    ImportKvpncSettingsAction = new KAction(KIcon("arrow-down-double"), i18n("Import KVpnc settings..."), actionCollection());
    ImportKvpncSettingsAction->setShortcut(Qt::Key_O);
    actionCollection()->addAction("importKvpncSettings", ImportKvpncSettingsAction);
    connect(ImportKvpncSettingsAction, SIGNAL(triggered()), SLOT(importKvpncSettingsClicked()));

    ExportKvpncSettingsAction = new KAction(KIcon("arrow-up-double"), i18n("Export KVpnc settings to file"), actionCollection());
    ExportKvpncSettingsAction->setShortcut(Qt::Key_E);
    actionCollection()->addAction("exportKvpncSettings", ExportKvpncSettingsAction);
    connect(ExportKvpncSettingsAction, SIGNAL(triggered()), SLOT(exportKvpncSettingsClicked()));

    ConnectAction = new KAction(KIcon("connected"), i18n("&Connect"), actionCollection());
    ConnectAction->setShortcut(Qt::CTRL + Qt::Key_Up);
    actionCollection()->addAction("serverConnect", ConnectAction);
    connect(ConnectAction, SIGNAL(triggered()), SLOT(slotConnecting()));

    DisconnectAction = new KAction(KIcon("disconnected"), i18n("&Disconnect"), actionCollection());
    DisconnectAction->setShortcut(Qt::CTRL + Qt::Key_Down);
    actionCollection()->addAction("serverDisconnect", DisconnectAction);
    connect(DisconnectAction, SIGNAL(triggered()), SLOT(disconnectClicked()));

    ProfileManagerAction = new KAction(KIcon("format-list-unordered"), i18n("&Manage Profiles"), actionCollection());
    ProfileManagerAction->setShortcut(Qt::CTRL + Qt::Key_M);
    actionCollection()->addAction("profileManager", ProfileManagerAction);
    connect(ProfileManagerAction, SIGNAL(triggered()), SLOT(showProfileManagerClicked()));

    NewProfileWizardAction = new KAction(KIcon("tools-wizard"), i18n("&new Profile (Wizard)"), actionCollection());
    NewProfileWizardAction->setShortcut(Qt::CTRL + Qt::Key_M);
    actionCollection()->addAction("NewProfileWizard", NewProfileWizardAction);
    connect(NewProfileWizardAction, SIGNAL(triggered()), SLOT(showNewProfileWizardClicked()));

    DonateAction = new KAction(KIcon("donate"), i18n("&Support KVpnc..."), actionCollection());
    DonateAction->setShortcut(Qt::CTRL + Qt::Key_D);
    actionCollection()->addAction("donate", DonateAction);
    connect(DonateAction, SIGNAL(triggered()), SLOT(donateClicked()));

    VisitHomepageAction = new KAction(KIcon("connected"), i18n("&Visit project homepage..."), actionCollection());
    VisitHomepageAction->setShortcut(Qt::CTRL + Qt::Key_R);
    actionCollection()->addAction("visithomepage", VisitHomepageAction);
    connect(VisitHomepageAction, SIGNAL(triggered()), SLOT(visitHomepageClicked()));

    DebugconsoleAction = new KToggleAction(KIcon("edit-select-all"), i18n("Toggle Debug &Console"), actionCollection());
    DebugconsoleAction->setShortcut(Qt::CTRL + Qt::Key_C);
    actionCollection()->addAction("debugconsole", DebugconsoleAction);
    connect(DebugconsoleAction, SIGNAL(triggered()), SLOT(toggleDebugConsole()));

    ToolsInfoAction = new KToggleAction(KIcon("help-about"), i18n("Show &Tools Info"), actionCollection());
    ToolsInfoAction->setShortcut(Qt::CTRL + Qt::Key_T);
    actionCollection()->addAction("toolsinfo", ToolsInfoAction);
    connect(ToolsInfoAction, SIGNAL(triggered()), SLOT(toolsInfoClicked()));
    // // tmp
    //connect(ToolsInfoAction, SIGNAL(triggered()), SLOT(helpClicked()));

    VpnTypesInfoAction = new KToggleAction(KIcon("help-about"),  i18n("Show &VPN types Info"), actionCollection());
    VpnTypesInfoAction->setShortcut(Qt::CTRL + Qt::Key_V);
    actionCollection()->addAction("vpntypesinfo", VpnTypesInfoAction);
    connect(VpnTypesInfoAction, SIGNAL(triggered()), SLOT(vpnTypesInfoClicked()));

    LogViewerAction = new KToggleAction(KIcon("format-list-ordered"), i18n("Show &Log"), actionCollection());
    LogViewerAction->setShortcut(Qt::CTRL + Qt::Key_L);
    actionCollection()->addAction("logviewer", LogViewerAction);
    connect(LogViewerAction, SIGNAL(triggered()), SLOT(showLogViewer()));


    GenerateOpenvpnKeyAction = new KToggleAction(KIcon("dialog-password"), i18n("Generate OpenVPN Key"), actionCollection());
    GenerateOpenvpnKeyAction->setShortcut(Qt::CTRL + Qt::Key_G);
    actionCollection()->addAction("genOpenvpncKey", GenerateOpenvpnKeyAction);
    connect(GenerateOpenvpnKeyAction, SIGNAL(triggered()), SLOT(generateOpenvpnKey()));


    SendFeedbackMailAction = new KAction(KIcon("mail-reply-sender"), i18n("Send &Feedback Mail..."), actionCollection());
//  SendFeedbackMailAction->setShortcut(0);
    actionCollection()->addAction("help_send_feedback_mail", SendFeedbackMailAction);
    connect(SendFeedbackMailAction, SIGNAL(triggered()), SLOT(sendFeedbackMail()));

    PrefAction = KStandardAction::preferences(this, SLOT(slotSettings()), actionCollection());
    KStandardAction::helpContents(this, SLOT(helpClicked()), actionCollection());
    KStandardAction::configureNotifications(this, SLOT(slotConfigNotifications()), actionCollection());
    KStandardAction::keyBindings(this, SLOT(slotKeyBindings()), actionCollection());

    this->ConnectAction->setEnabled(false);
    this->DisconnectAction->setEnabled(false);

    //  ShowToolbarAction = KStandardAction::showToolbar( this, SLOT( slotShowToolbar() ), actionCollection() );
    createStandardStatusBarAction();
    ShowStatusbarAction = KStandardAction::showStatusbar(this, SLOT(slotShowStatusbar()), actionCollection());
    PreferencesAction = KStandardAction::preferences(this, SLOT(slotSettings()), actionCollection());

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

    createGUI();

}

void KVpnc::initView()
{

    mw = new MainView(this);
    setCentralWidget(mw);

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

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

    mw->SessionCombo->setEnabled(false);

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


    statusColorLabel->setPixmap(disconnectedStatusPixmap);
    statusBar()->addPermanentWidget(statusColorLabel, 0);
}

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

void KVpnc::initDockWindow()
{
    KVpncDock = new KVpncKicker(GlobalConfig, this, "kickerIcon");
    KVpncDock->menu()->addAction(ConnectAction);
    KVpncDock->menu()->addAction(DisconnectAction);
    KVpncDock->menu() ->insertSeparator(DisconnectAction);
    KVpncDock->menu()->addAction(PreferencesAction);
    connect (KVpncDock, SIGNAL(showTooltipRequested(const QPoint &)), this, SLOT(showDockTooltip(const QPoint &)));
}

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

    prefDlg = new PreferencesDialog((QWidget *) this, parent, (QTextEdit *) mw->DebugOutput, GlobalConfig, showProfilesOnly);
//  prefDlg->setMinimumSize ( 800, 600 );

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

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

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

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

    }
    if (prefDlg->profileHasChanged) {
        mw->SessionCombo->setCurrentItem(prefDlg->NewProfileName);
        sessionToggled(prefDlg->NewProfileName);
    }

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

    if (GlobalConfig->writeLogFile) {
        if (!GlobalConfig->logfile.isOpen()) {
            KStandardDirs * dirs = KGlobal::dirs();
            QString logfileName = QString(dirs->saveLocation("data"));
            QString logfilePath = QString(logfileName + "/kvpnc/kvpnc.log");
            //KMessageBox::information( this, "info", logfileName );
            GlobalConfig->logfile.setFileName(logfileName);
            if (!GlobalConfig->logfile.open(QIODevice::WriteOnly | QIODevice::Append)) {
                KMessageBox::error(this, i18n("Log file cannot be opened."));
                GlobalConfig->appendLogEntry(i18n("Log file cannot be opened.") , KVpncEnum::error);
            } else {
                GlobalConfig->logFileStream << i18n("Log session started at: ") << QDateTime::currentDateTime().toString(Qt::TextDate) << endl;
            }
        }
    } else {
        if (GlobalConfig->logfile.isOpen()) {
            //QTextStream s( &logfile );
            GlobalConfig->logFileStream << i18n("Log session ended at: ") << QDateTime::currentDateTime().toString(Qt::TextDate) << endl;
            GlobalConfig->logfile.close();
        }
    }
    //GlobalConfig->saveOptions();
    //saveGuiOptions();
    saveSessionClicked();
    showProfilesOnly = false;
    disconnect ( prefDlg->ProfileGeneralOptionsWidget->NewSessionPushButton , SIGNAL ( clicked () ), this, SLOT ( showNewProfileWizardClicked() ) );
    disconnect ( this, SIGNAL(newProfileCreated(QString )), prefDlg, SLOT(slotProfileCreated(QString )));
    delete prefDlg;
}

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

void KVpnc::slotShowStatusbar()
{

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

void KVpnc::slotKeyBindings()
{

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

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

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

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

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

}

void KVpnc:: quitCalled()
{
    bool reallyQuit = false;
    if (GlobalConfig->KvpncDebugLevel > 1)
        GlobalConfig->appendLogEntry(i18n("quitCalled()"), KVpncEnum::debug);
    QString TypeString = "";

    if (GlobalConfig->currentProfile != 0) {
        if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco)
            TypeString =  i18n("Cisco");
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig)
            TypeString =  i18n("Cisco (proprietary)");
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp)
            TypeString =  i18n("PPTP");
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon)
            TypeString =  i18n("racoon");
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan)
            TypeString = IpsecType;
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn)
            TypeString =  i18n("OpenVPN");
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon)
            TypeString =  i18n("L2TP (racoon)");
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan)
            TypeString = IpsecType;
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::vtun)
            TypeString = i18n("Vtun");
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh)
            TypeString = i18n("SSH");
        else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_plain )
            TypeString = i18n ( "L2TP (plain)" );
        else
            TypeString = i18n("other");
    }

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

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

    } else {
        reallyQuit = true;
        if (reallyQuit) {
            if (!GlobalConfig->AccountList->isEmpty())
                if (GlobalConfig->currentProfile != 0)
                    GlobalConfig->lastProfile = GlobalConfig->currentProfile->getName();


            saveGuiOptions();
            GlobalConfig->saveOptions();
            restoreNetworkEnvironment();
            tmpPath = KStandardDirs::locateLocal("data", "kvpnc/");
            QFile file(tmpPath + "kvpnc_running");
            file.remove();
            if (GlobalConfig->writeLogFile) {
                if (GlobalConfig->logfile.isOpen()) {
                    //     QTextStream s( &logfile );
                    GlobalConfig->logFileStream << i18n("Log session ended at: ") << QDateTime::currentDateTime().toString(Qt::TextDate) << endl;
                    GlobalConfig->logfile.flush();
                    GlobalConfig->logfile.close();
                    GlobalConfig->appPointer->processEvents();
                }
            }
            kapp->quit();
        }
    }
}

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

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

void KVpnc::closeEvent(QCloseEvent *e)
{
    if (GlobalConfig->KvpncDebugLevel > 1)
        GlobalConfig->appendLogEntry(i18n("CloseEvent received (receiver: %1)." , QString("kvpnc")), KVpncEnum::debug);

    QString TypeString = "";
    if (GlobalConfig->currentProfile != 0) {
        if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco)
            TypeString =  i18n("Cisco");
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig)
            TypeString =  i18n("Cisco (proprietary)");
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp)
            TypeString =  i18n("PPTP");
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon)
            TypeString =  i18n("racoon");
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan)
            TypeString = IpsecType;
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn)
            TypeString =  i18n("OpenVPN");
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon)
            TypeString =  i18n("L2TP (racoon)");
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan)
            TypeString = IpsecType;
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::vtun)
            TypeString = i18n("Vtun");
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh)
            TypeString = i18n("SSH");
        else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_plain )
            TypeString = i18n ( "L2TP (plain)" );
        else
            TypeString = i18n("other");
    }

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

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

                            if (GlobalConfig->writeLogFile) {
                                if (GlobalConfig->logfile.isOpen()) {
                                    //        QTextStream s( &logfile );
                                    GlobalConfig->logFileStream << i18n("Log session ended at: ") << QDateTime::currentDateTime().toString(Qt::TextDate) << endl;
                                    GlobalConfig->logfile.close();
                                    GlobalConfig->appPointer->processEvents();
                                }
                            }
                            tmpPath = KStandardDirs::locateLocal("data", "kvpnc/");
                            QFile file(tmpPath + "kvpnc_running");
                            file.remove();

                            KMainWindow::closeEvent(e);
                        }
                    }
                } else {
                    //disconnect and quit silently
                    GlobalConfig->skipKwalletStoring = true;
                    disconnectClicked();
                    reallyQuit = true;
                }
            }
        } else {
            reallyQuit = true;
            GlobalConfig->skipKwalletStoring = true;
        }

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

bool KVpnc::queryExit()
{
    if (GlobalConfig->KvpncDebugLevel > 1)
        GlobalConfig->appendLogEntry(i18n("queryExit received (receiver: %1)." , QString("kvpnc")), KVpncEnum::debug);
    kDebug() << "KVpnc::queryExit()" << endl;

    if (GlobalConfig->status == KVpncEnum::connecting || GlobalConfig->status == KVpncEnum::connected) {
        disconnectClicked();
    }

    if (!kapp->sessionSaving()) {
        if (GlobalConfig->KvpncDebugLevel > 1)
            GlobalConfig->appendLogEntry(i18n("KVpnc::queryExit(): not saving session."), KVpncEnum::debug);
    } else {
        if (GlobalConfig->KvpncDebugLevel > 1)
            GlobalConfig->appendLogEntry(i18n("KVpnc::queryExit(): saving session"), KVpncEnum::debug);
        GlobalConfig->saveOptions();
        saveGuiOptions();

    }

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

    return true;
}

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

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

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

void KVpnc::restore(KConfig *config, int i)
{
    readPropertiesInternal(config, i);
}

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

    if (!config)
        return;

    return;
}

void KVpnc::saveProperties(KConfigGroup &c)
{
    Q_UNUSED(c);

    QString saveDir = KGlobal::dirs()->saveLocation("appdata",
                      "sessions/" + qApp->sessionId() + "/",
                      true);
    KConfigGroup configgroup = KGlobal::config()->group("Saved Session");
}

void KVpnc::readProperties(const KConfigGroup &c)
{
    Q_UNUSED(c);

    QString saveDir = KGlobal::dirs()->saveLocation("appdata",
                      "sessions/" + qApp->sessionId() + "/",
                      true);
    KConfigGroup configgroup = KGlobal::config()->group("Saved Session");
}

void KVpnc::connectClicked()
{
    ConnectAction->setEnabled(false);

    TunnelInterfaceIP = i18n("None");

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

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

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

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

    /* update dns? */
    if (GlobalConfig->currentProfile->getUseDnsUpdate()) {
        if (! backupResolvConf()) {
            //    if ( GlobalConfig->KvpncDebugLevel > 0 )
            GlobalConfig->appendLogEntry(i18n("Connect canceled because a backup of %1 could not be created." , QString("/etc/resolv.conf")), KVpncEnum::error);
            return ;
        }
    }

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

        //setGuiStatus(connecting);

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

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


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

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

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

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


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

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

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

            if (AuthRetry)
                askUsernamePass = true;

            bool requestUsername = false;
            bool requestGroupPassword = true;

            if (!GlobalConfig->haveUserData) {
                if (!GlobalConfig->currentProfile->getSavePsk())
                    askUsernamePass = true;

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

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

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



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

                if (GlobalConfig->currentProfile->getHideGroupPasswordInAccountDataDialog())
                    requestGroupPassword = false;
            } else {
                if (GlobalConfig->KvpncDebugLevel > 4)
                    GlobalConfig->appendLogEntry(i18n("User data already collected."), KVpncEnum::debug);
            }

            if (GlobalConfig->currentProfile->getAskUserPasswordOnEachConnect()) {
                if (GlobalConfig->KvpncDebugLevel > 4)
                    GlobalConfig->appendLogEntry(i18n("User password on each connect forced."), KVpncEnum::debug);

                askUsernamePass = true;
                requestUsername = true;
            }


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

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

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

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

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

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

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

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

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

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

                    bool askGroupPass = false;

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

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

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

                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("Some account data which was needed was obtained from a password dialog."), KVpncEnum::debug);

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

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

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

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


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

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

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

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

            //   QString tunneldevice = "tun0";
            OldDefaultroute = tmpPath + "default-route." + GlobalConfig->currentProfile->getName(); // default-route.<id>

//             QFile DefaultRouteBackupFile(OldDefaultroute + ".sh");
//             QTextStream DefaultRouteBackupFileStream(&DefaultRouteBackupFile);
//             if (DefaultRouteBackupFile.open(QIODevice::WriteOnly)) {
//                 DefaultRouteBackupFileStream << "# generated by kvpnc. Do not edit it." << "\n";
//                 DefaultRouteBackupFileStream << "\n";
//                 DefaultRouteBackupFileStream << GlobalConfig->pathToIp + " route show | grep default > " + OldDefaultroute + "\n";
//                 DefaultRouteBackupFile.close();
//                 QProcess backupDefaultRouteProcess(this);
//                 QString proc = GlobalConfig->InterpreterShell;
//                 QStringList args;
//       backupDefaultRouteProcess.setEnvironment(*env);
//                 args.append(OldDefaultroute + ".sh");
//                 backupDefaultRouteProcess.setEnvironment(*env);
//                 backupDefaultRouteProcess.start(proc,args);
//                 if (!backupDefaultRouteProcess.waitForStarted()) {
//                     //     if ( GlobalConfig->KvpncDebugLevel > 0 )
//                     GlobalConfig->appendLogEntry(i18n("Connect canceled because default route backup process could not be started."), KVpncEnum::error);
//                     return ;
//                 } else {
//                     if (GlobalConfig->KvpncDebugLevel > 2)
//                         GlobalConfig->appendLogEntry(i18n("Default route backup process started."), KVpncEnum::debug);
//                     backupDefaultRouteProcess.waitForFinished();
//
//                 }
//             } else {
//                 //    if ( GlobalConfig->KvpncDebugLevel > 0 )
//                 GlobalConfig->appendLogEntry(i18n("Connect canceled because a backup of the default route could not be created."), KVpncEnum::error);
//                 return ;
//             }
            backupDefaultRoute();

            VpncGateway = tmpPath + "gateway." + GlobalConfig->currentProfile->getName(); // gateway.<id>
            VpncConnectScript = tmpPath + "vpnc-connect." + GlobalConfig->currentProfile->getName() + ".sh"; // vpnc-connect.<id>.sh
            GlobalConfig->Vpnc_pid_file = tmpPath + "vpnc-pid." + GlobalConfig->currentProfile->getName() + ".pid"; // vpnc-pid.<id>.pid

            // write vpnc connect script
            VpncScript = tmpPath + "vpnc-script." + GlobalConfig->currentProfile->getName(); // vpnc-script.<name>
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry("VpncScript: " + VpncScript + "\n", KVpncEnum::debug);
            QFile file(VpncScript);
            QTextStream stream(&file);
            if (file.open(QIODevice::WriteOnly)) {
                stream <<  "#!" << GlobalConfig->InterpreterShell << "\n";
                stream << "#* reason                       -- why this script was called, one of: pre-init connect disconnect\n";
                stream << "#* VPNGATEWAY                   -- vpn gateway address (always present)\n";
                stream << "#* TUNDEV                       -- tunnel device (always present)\n";
                stream << "#* INTERNAL_IP4_ADDRESS         -- address (always present)\n";
                stream << "#* INTERNAL_IP4_NETMASK         -- netmask (often unset)\n";
                stream << "#* INTERNAL_IP4_DNS             -- list of dns serverss\n";
                stream << "#* INTERNAL_IP4_NBNS            -- list of wins servers\n";
                stream << "#* CISCO_DEF_DOMAIN             -- default domain name\n";
                stream << "#* CISCO_BANNER                 -- banner from server\n";
                stream << "#* CISCO_SPLIT_INC              -- number of networks in split-network-list\n";
                stream << "#* CISCO_SPLIT_INC_%d_ADDR      -- network address\n";
                stream << "#* CISCO_SPLIT_INC_%d_MASK      -- subnet mask (for example: 255.255.255.0)\n";
                stream << "#* CISCO_SPLIT_INC_%d_MASKLEN   -- subnet masklen (for example: 24)\n";
                stream << "#* CISCO_SPLIT_INC_%d_PROTOCOL  -- protocol (often just 0)\n";
                stream << "#* CISCO_SPLIT_INC_%d_SPORT     -- source port (often just 0)\n";
                stream << "#* CISCO_SPLIT_INC_%d_DPORT     -- destination port (often just 0)\n";
                stream << "\n";
                stream << "#set -x\n";
                stream << "\n";
                stream << "OS=\"`uname -s`\"\n";
                stream << "DEFAULT_ROUTE_FILE=/var/run/vpnc/defaultroute\n";
                stream << "RESOLV_CONF_BACKUP=" + tmpPath + "resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() + "\n";
                stream << "\n";
                stream << "IPROUTE=" + GlobalConfig->pathToIp + "\n";
                stream << "\n";
                stream << "if [ \"$OS\" = \"Linux\" ]; then\n";
                stream << " ifconfig_syntax_ptp=\"pointopoint\"\n";
                stream << " route_syntax_gw=\"gw\"\n";
                stream << " route_syntax_del=\"del\"\n";
                stream << " route_syntax_netmask=\"netmask\"\n";
                stream << "else\n";
                stream << " ifconfig_syntax_ptp=\"\"\n";
                stream << " route_syntax_gw=\"\"\n";
                stream << " route_syntax_del=\"delete\"\n";
                stream << " route_syntax_netmask=\"-netmask\"\n";
                stream << "fi\n";
                stream << "\n";
                stream << "####\n";
                stream << "\n";
                stream << "kernel_is_2_6_or_above()\n";
                stream << "{\n";
                stream << " case \"$(uname -r)\" in\n";
                stream << "  1.*|2.[012345]*) return 1 ;;\n";
                stream << "  *) return 0 ;;\n";
                stream << " esac\n";
                stream << "}\n";
                stream << "\n";
                stream << "udev_is_active()\n";
                stream << "{\n";
                stream << " test -e /dev/.udev.tdb || test -d /dev/.udevdb || return 1\n";
                stream << " kernel_is_2_6_or_above || return 1\n";
                stream << " return 0\n";
                stream << "}\n";
                stream << "\n";
                stream << "\n";
                stream << "do_pre_init() {\n";
                stream << " if [ \"$OS\" = \"Linux\" ]; then\n";
                stream << "  if (exec 6<> /dev/net/tun) > /dev/null 2>&1 ; then\n";
                stream << "   :\n";
                stream << "  else # can't open /dev/net/tun\n";
                stream << "   test -e /proc/sys/kernel/modprobe && `cat /proc/sys/kernel/modprobe` tun 2>/dev/null\n";
                stream << "   # fix for broken devfs in kernel 2.6.x\n";
                stream << "   if [ \"`readlink /dev/net/tun`\" = misc/net/tun \\\n";
                stream << "    -a ! -e /dev/net/misc/net/tun -a -e /dev/misc/net/tun ] ; then\n";
                stream << "    ln -sf /dev/misc/net/tun /dev/net/tun\n";
                stream << "   fi\n";
                stream << "   # make sure tun device exists\n";
                stream << "   if [ ! -e /dev/net/tun ]; then\n";
                stream << "    mkdir -p /dev/net\n";
                stream << "    mknod -m 0640 /dev/net/tun c 10 200\n";
                stream << "   fi\n";
                stream << "\n";
                stream << "            # workaround for a possible latency caused by udev, sleep max. 10s\n";
                stream << "            if udev_is_active ; then\n";
                stream << "                for x in `seq 100` ; do\n";
                stream << "                    (exec 6<> /dev/net/tun) > /dev/null 2>&1 && break;\n";
                stream << "                    sleep 0.1\n";
                stream << "                done\n";
                stream << "            fi\n";
                stream << "  fi\n";
                stream << " elif [ \"$OS\" = \"FreeBSD\" ]; then\n";
                stream << "  if [ ! -e /dev/tun ]; then\n";
                stream << "   kldload if_tun\n";
                stream << "  fi\n";
                stream << " elif [ \"$OS\" = \"NetBSD\" ]; then\n";
                stream << "  :\n";
                stream << " elif [ \"$OS\" = \"OpenBSD\" ]; then\n";
                stream << "  :\n";
                stream << " elif [ \"$OS\" = \"SunOS\" ]; then\n";
                stream << "  :\n";
                stream << " fi\n";
                stream << "}\n";
                stream << "\n";
                stream << "do_ifconfig() {\n";
                if (GlobalConfig->currentProfile->getUseMtu())
                    stream << GlobalConfig->pathToIfconfig + " \"$TUNDEV\" inet \"$INTERNAL_IP4_ADDRESS\" $ifconfig_syntax_ptp \"$INTERNAL_IP4_ADDRESS\" netmask 255.255.255.255 mtu " + QString().setNum(GlobalConfig->currentProfile->getMtu()) + " up\n";
                else
                    stream << GlobalConfig->pathToIfconfig + " \"$TUNDEV\" inet \"$INTERNAL_IP4_ADDRESS\" $ifconfig_syntax_ptp \"$INTERNAL_IP4_ADDRESS\" netmask 255.255.255.255 mtu 1390 up\n";
                stream << "}\n";
                stream << "\n";
                stream << "if [ -n \"$IPROUTE\" ]; then\n";
                stream << " fix_ip_get_output () {\n";
//   stream << "  sed 's/cache//;s/metric \\?[0-9]\\+ [0-9]\\+//g'\n"; // (works on etch)
                stream << "  sed 's/cache//;s/metric[ 0-9]\\+//g;s/hoplimit[ 0-9]\\+//g'" << "\n"; // sed 's/cache//;s/metric[ 0-9]\+//g;s/hoplimit[ 0-9]\+//g' (works on fc6)
                stream << " }\n";
                stream << "\n";
                stream << " set_vpngateway_route() {\n";
                stream << "  $IPROUTE route add `" + GlobalConfig->pathToIp + " route get \"$VPNGATEWAY\" | fix_ip_get_output`\n";
                stream << "  $IPROUTE route flush cache\n";
                stream << " }\n";
                stream << " \n";
                stream << " del_vpngateway_route() {\n";
                stream << "  $IPROUTE route del \"$VPNGATEWAY\"\n";
                stream << "  $IPROUTE route flush cache\n";
                stream << " }\n";
                stream << " \n";
                stream << " set_default_route() {\n";
                if (GlobalConfig->currentProfile->getReplaceDefaultRoute()) {
                    stream << "  mkdir -p /var/run/vpnc\n";
                    stream << "  $IPROUTE route | grep '^default' | fix_ip_get_output > \"$DEFAULT_ROUTE_FILE\"\n";
                    stream << "  $IPROUTE route del default\n";
                    stream << "  $IPROUTE route add default dev \"$TUNDEV\"\n";
                    stream << "  $IPROUTE route flush cache\n";
                } else {
                    stream << "  echo \"\"\n";
                }
                stream << " }\n";
                stream << " \n";
                stream << " set_network_route() {\n";
                stream << "  NETWORK=\"$1\"\n";
                stream << "  NETMASK=\"$2\"\n";
                stream << "  NETMASKLEN=\"$3\"\n";
                stream << "  $IPROUTE route add \"$NETWORK/$NETMASKLEN\" dev \"$TUNDEV\"\n";
                stream << "  $IPROUTE route flush cache\n";
                stream << " }\n";
                stream << " \n";
                stream << " reset_default_route() {\n";
                stream << "  $IPROUTE route del default > /dev/null 2>&1\n";
                stream << "  $IPROUTE route add `cat \"$DEFAULT_ROUTE_FILE\"`\n";
                stream << "  $IPROUTE route flush cache\n";
                stream << " }\n";
                stream << " \n";
                stream << " del_network_route() {\n";
//     if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() )
//     {
//      stream << "  # linux deletes routes automatically if the device is shut down\n";
//      stream << "  return\n";
//     }
                stream << "  #NETWORK=\"$1\"\n";
                stream << "  #NETMASK=\"$2\"\n";
                stream << "  #NETMASKLEN=\"$3\"\n";
                if (GlobalConfig->currentProfile->getReplaceDefaultRoute())
                    stream << "  #$IPROUTE route del \"$NETWORK/$NETMASKLEN\" dev \"$TUNDEV\" \n";
                else
                    stream << "  #$IPROUTE route del \"$NETWORK/$NETMASKLEN\" dev \"" + tmpInterface + "\"\n";
                stream << "  #$IPROUTE route flush cache\n";
                stream << "  # linux deletes routes automatically if the device is shut down\n";
                stream << "  echo \"\"\n";
                stream << " }\n";
                stream << "else\n";
                stream << " get_default_gw() {\n";
                stream << "  # solaris again ...\n";
                stream << "  netstat -r -n | sed 's/default/0.0.0.0/' | grep '^0.0.0.0' | awk '{print $2}'\n";
                stream << " }\n";
                stream << " \n";
                stream << " set_vpngateway_route() {\n";
                stream << "  " + GlobalConfig->pathToRoute + " add -host \"$VPNGATEWAY\" $route_syntax_gw \"`get_default_gw`\"\n";
                stream << " }\n";
                stream << "\n";
                stream << " del_vpngateway_route() {\n";
                stream << "  " + GlobalConfig->pathToRoute + " $route_syntax_del -host \"$VPNGATEWAY\"\n";
                stream << " }\n";
                stream << " \n";
                stream << " set_default_route() {\n";
                if (GlobalConfig->currentProfile->getReplaceDefaultRoute()) {
                    stream << "  DEFAULTGW=\"`get_default_gw`\"\n";
                    stream << "  echo \"$DEFAULTGW\" > \"$DEFAULT_ROUTE_FILE\"\n";
                    stream << "  route $route_syntax_del default \"$DEFAULTGW\"\n";
                    stream << "  route add default $route_syntax_gw \"$INTERNAL_IP4_ADDRESS\"\n";
                } else {
                    stream << "  echo \"\"\n";
                }
                stream << " }\n";
                stream << " \n";
                stream << " set_network_route() {\n";
                stream << "  NETWORK=\"$1\"\n";
                stream << "  NETMASK=\"$2\"\n";
                stream << "  NETMASKLEN=\"$3\"\n";
                stream << "  route add -net \"$NETWORK\" $route_syntax_netmask \"$NETMASK\" $route_syntax_gw \"$INTERNAL_IP4_ADDRESS\"\n";
                stream << " }\n";
                stream << " \n";
                stream << " reset_default_route() {\n";
                if (GlobalConfig->currentProfile->getReplaceDefaultRoute()) {
                    stream << "  route $route_syntax_del default\n";
                    stream << "  route add default $route_syntax_gw `cat \"$DEFAULT_ROUTE_FILE\"`\n";
                } else {
                    stream << "  echo \"\"\n";
                }
                stream << " }\n";
                stream << " \n";
                stream << " del_network_route() {\n";
                stream << "  if [ \"$OS\" = \"Linux\" ]; then\n";
                stream << "   # linux deletes routes automatically if the device is shut down\n";
                stream << "   return\n";
                stream << "  fi\n";
                stream << "  NETWORK=\"$1\"\n";
                stream << "  NETMASK=\"$2\"\n";
                stream << "  NETMASKLEN=\"$3\"\n";
                stream << "  route $route_syntax_del -net \"$NETWORK\" $route_syntax_netmask \"$NETMASK\" $route_syntax_gw \"$INTERNAL_IP4_ADDRESS\"\n";
                stream << " }\n";
                stream << "fi\n";
                stream << "\n";
                stream << "write_resolvconf() {\n";
                stream << "\n";
                /* update dns? */
                if ( GlobalConfig->currentProfile->getUseDnsUpdate() ) {
                    stream << "    cat /etc/resolv.conf > " + tmpPath + "resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() + "\n";
                    stream << "    if [ -f /sbin/resolvconf ] ; then\n";
                    stream << "        mkdir -p /var/run/vpnc\n";
                    stream << "        ( \n";
                    stream << "        if [ \"$CISCO_DEF_DOMAIN\" ] ; then\n";
                    stream << "            echo domain \"$CISCO_DEF_DOMAIN\"\n";
                    stream << "            echo search \"$CISCO_DEF_DOMAIN\"\n";
                    stream << "        fi\n";
                    stream << "        nameserver_found=0\n";
                    stream << "        for ip in \"$INTERNAL_IP4_DNS\" ; do\n";
                    stream << "            echo nameserver $ip\n";
                    stream << "            nameserver_found=1\n";
                    stream << "        done\n";
                    stream << "        if [ \"$nameserver_found\" = \"0\" ]; then" << "\n";
                    stream << "           echo \"# old nameserver\"\n";
                    stream << "           cat   "+tmpPath + "/resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() +" | grep nameserver\n";
                    stream << "        fi" << "\n";
                    stream << "        ) > /var/run/vpnc/resolvconf\n";
                    stream << "       cat /var/run/vpnc/resolvconf | /sbin/resolvconf -a $TUNDEV\n";

                    /* crissi: -u seems not nessesary */
                    //stream << "       cat /var/run/vpnc/resolvconf | /sbin/resolvconf -u\n";

                    stream << "        return\n";
                    stream << "    fi\n";
                    stream << "\n";
                    stream << "	grep '^#@VPNC_GENERATED@' /etc/resolv.conf > /dev/null 2>&1 || cp -- /etc/resolv.conf \"$RESOLV_CONF_BACKUP\"\n";
                    stream << "	NEW_RESOLVCONF=\"#@VPNC_GENERATED@ -- this file is generated by vpnc\n";
                    stream << "# and will be overwritten by vpnc\n";
                    stream << "# as long as the above mark is intact\"\n";
                    stream << "	\n";
                    stream << "	exec 6< /etc/resolv.conf\n";
                    stream << "	while read LINE <&6 ; do\n";
                    stream << "		case \"$LINE\" in\n";
                    stream << "			nameserver*)\n";
                    stream << "				if [ -n \"$INTERNAL_IP4_DNS\" ]; then\n";
                    stream << "					read ONE_NAMESERVER INTERNAL_IP4_DNS <<-EOF\n";
                    stream << "	$INTERNAL_IP4_DNS\n";
                    stream << "EOF\n";
                    stream << "					LINE=\"nameserver $ONE_NAMESERVER\"\n";
                    stream << "				else\n";
                    stream << "					LINE=""\n";
                    stream << "				fi\n";
                    stream << "				;;\n";
                    stream << "			domain*|search*)\n";
                    stream << "				if [ -n \"$CISCO_DEF_DOMAIN\" ]; then\n";
                    stream << "					LINE=\"$LINE $CISCO_DEF_DOMAIN\"\n";
                    stream << "					CISCO_DEF_DOMAIN=""\n";
                    stream << "				fi\n";
                    stream << "				;;\n";
                    stream << "		esac\n";
                    stream << "		NEW_RESOLVCONF=\"$NEW_RESOLVCONF\n";
                    stream << "$LINE\"\n";
                    stream << "	done\n";
                    stream << "	exec 6<&-\n";
                    stream << "	\n";
                    stream << "	for i in $INTERNAL_IP4_DNS ; do\n";
                    stream << "		NEW_RESOLVCONF=\"$NEW_RESOLVCONF\n";
                    stream << "nameserver $i\"\n";
                    stream << "	done\n";
                    stream << "	if [ -n \"$CISCO_DEF_DOMAIN\" ]; then\n";
                    stream << "		NEW_RESOLVCONF=\"$NEW_RESOLVCONF\n";
                    stream << "search $CISCO_DEF_DOMAIN\"\n";
                    stream << "	fi\n";
                    stream << "	echo \"$NEW_RESOLVCONF\" > /etc/resolv.conf\n";

                } else {
                    /* dont update dns */
                    setenv ( "DNS_UPDATE", "NO",1 );
                    stream << "        return\n";
                }
                stream << "}\n";
                stream << "\n";
                stream << "reset_resolvconf() {\n";
                stream << "\n";
                /* update dns? */
                if ( GlobalConfig->currentProfile->getUseDnsUpdate() ) {
                    // 					stream << "    case \"$DNS_UPDATE\" in\n";
                    // 					stream << "        *no|*NO|*No|*nO)\n";
                    // 					stream << "        return\n";
                    // 					stream << "        ;;\n";
                    // 					stream << "    esac\n";
                    // 					stream << "\n";
                    stream << "    if [ -f /sbin/resolvconf ] ; then\n";
                    stream << "        /sbin/resolvconf -d \"$TUNDEV\"\n";
                    stream << "        return\n";
                    stream << "    else\n";
                    stream << "        cat " + tmpPath + "resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() + " > /etc/resolv.conf\n";
                    stream << "    fi\n";
                } else {

                    /* dont update dns */
                    setenv ( "DNS_UPDATE", "NO",1 );
                    stream << "	return\n";
                }
                stream << "}\n";
                stream << "\n";
                stream << "do_connect() {\n";
                stream << "    # Debian specific, insert your code there to avoid modification of\n";
                stream << "    # conffiles like this script\n";
                stream << "    if [ -r /etc/vpnc/vpnc-script-connect-action ] ; then\n";
                stream << "        . /etc/vpnc/vpnc-script-connect-action\n";
                stream << "    fi\n";
                stream << " if [ -n \"$CISCO_BANNER\" ]; then\n";
                stream << "  echo \"Connect Banner:\"\n";
                stream << "  echo \"$CISCO_BANNER\" | while read LINE ; do echo \"|\" \"$LINE\" ; done\n";
                stream << "  echo\n";
                stream << " fi\n";
                stream << " \n";
                stream << " do_ifconfig\n";
                stream << " set_vpngateway_route\n";
                stream << "\n";
                stream << "        # -- Debian specific\n";
                stream << "        if test \"$TARGET_NETWORKS\" ; then\n";
                stream << "            for network in $TARGET_NETWORKS ; do\n";
                stream << "                " + GlobalConfig->pathToIp + " route del $network 2>/dev/null\n";
                stream << "                " + GlobalConfig->pathToIp + " route add $network dev $TUNDEV\n";
                stream << "            done\n";
                stream << "        else\n";
                stream << "\n";
                stream << " if [ -n \"$CISCO_SPLIT_INC\" ]; then\n";
                stream << "  i=0\n";
                stream << "  while [ $i -lt $CISCO_SPLIT_INC ] ; do\n";
                stream << "   eval NETWORK=\"\\${CISCO_SPLIT_INC_${i}_ADDR}\"\n";
                stream << "   eval NETMASK=\"\\${CISCO_SPLIT_INC_${i}_MASK}\"\n";
                stream << "   eval NETMASKLEN=\"\\${CISCO_SPLIT_INC_${i}_MASKLEN}\"\n";
                stream << "   set_network_route \"$NETWORK\" \"$NETMASK\" \"$NETMASKLEN\"\n";
                stream << "   i=`expr $i + 1`\n";
                stream << "  done\n";
                stream << "  for i in $INTERNAL_IP4_DNS ; do\n";
                stream << "   set_network_route \"$i\" \"255.255.255.255\" \"32\"\n";
                stream << "  done\n";
                stream << " else\n";
                stream << "  set_default_route\n";
                stream << " fi\n";
                stream << "\n";
                stream << "        fi\n";
                stream << " \n";
                stream << " if [ -n \"$INTERNAL_IP4_DNS\" ]; then\n";
                stream << "  write_resolvconf\n";
                stream << " fi\n";
                stream << "}\n";
                stream << "\n";
                stream << "do_disconnect() {\n";
                stream << " # Debian specific, insert your code there to avoid modification of\n";
                stream << " # conffiles like this script\n";
                stream << " if [ -r /etc/vpnc/vpnc-script-disconnect-action ] ; then\n";
                stream << "  . /etc/vpnc/vpnc-script-disconnect-action\n";
                stream << "  fi\n";
                stream << " if [ -n \"$CISCO_SPLIT_INC\" ]; then\n";
                stream << "  i=0\n";
                stream << "  while [ $i -lt $CISCO_SPLIT_INC ] ; do\n";
                stream << "   eval NETWORK=\"\\${CISCO_SPLIT_INC_${i}_ADDR}\"\n";
                stream << "   eval NETMASK=\"\\${CISCO_SPLIT_INC_${i}_MASK}\"\n";
                stream << "   eval NETMASKLEN=\"\\${CISCO_SPLIT_INC_${i}_MASKLEN}\"\n";
                stream << "   del_network_route \"$NETWORK\" \"$NETMASK\" \"$NETMASKLEN\"\n";
                stream << "   i=`expr $i + 1`\n";
                stream << "  done\n";
                stream << "  for i in $INTERNAL_IP4_DNS ; do\n";
                stream << "   del_network_route \"$i\" \"255.255.255.255\" \"32\"\n";
                stream << "  done\n";
                stream << " else\n";
                stream << "  if [ -s \"$DEFAULT_ROUTE_FILE\" ]; then\n";
                stream << "   reset_default_route\n";
                stream << "   rm -f -- \"$DEFAULT_ROUTE_FILE\"\n";
                stream << "  fi\n";
                stream << " fi\n";
                stream << " \n";
                stream << " del_vpngateway_route\n";
                stream << " \n";
                stream << " if [ -n \"$INTERNAL_IP4_DNS\" ]; then\n";
                stream << "  reset_resolvconf\n";
                stream << " fi\n";
                stream << "}\n";
                stream << "\n";
                stream << "####\n";
                stream << "\n";
                stream << "if [ -z \"$reason\" ]; then\n";
                stream << " echo \"this script must be called from vpnc\" 1>&2\n";
                stream << " exit 1\n";
                stream << "fi\n";
                stream << "\n";

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

                file.close();
                if ( GlobalConfig->KvpncDebugLevel > 3 )
                    GlobalConfig->appendLogEntry ( i18n ( "Writing VpncScript finished." ), KVpncEnum::debug );
            }

        } else {
            GlobalConfig->appendLogEntry(i18n("Creating %1 has been failed." , QString("VpncScript")), KVpncEnum::error);
            setGuiStatus(KVpncEnum::disconnected);
            timer.stop();
            return ;
        }

        if (Utils(GlobalConfig).doChmod(VpncScript, "+x")) {

            //sleep ( 1 );
            if (GlobalConfig->KvpncDebugLevel > 3)
                GlobalConfig->appendLogEntry(i18n("Checking tun device support"), KVpncEnum::debug);

            //if (!NetworkInterface(GlobalConfig, parent, this).interfaceExist("tun0"))
            {                    //FIXME make it dynamiclly (tun+)
                QFile tundevfile("/dev/net/tun");
                if (!tundevfile.exists()) {
                    if (!Utils(GlobalConfig, parent).createTunDev()) {
                        KMessageBox::error(this, i18n("Failed to create \"%1\"." , QString("/dev/net/tun")));
                        GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, creating it has failed: stop."), KVpncEnum::error);
                        disconnectClicked();
                        setGuiStatus(KVpncEnum::disconnected);
                        GlobalConfig->status = KVpncEnum::disconnected;
                        return ;
                    } else {
                        if (GlobalConfig->KvpncDebugLevel > 0)
                            GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, creating was successful."), KVpncEnum::debug);
                    }
                }
                // load the module 'tun'


                if (GlobalConfig->KvpncDebugLevel > 3)
                    GlobalConfig->appendLogEntry(i18n("Checking tun support"), KVpncEnum::debug);
                bool tunsupportfound = false;
                QString procmisc = "";
                QFile f("/proc/misc");
                if (f.open(QIODevice::ReadOnly)) {
                    QTextStream stream(&f);
                    QStringList ProcMiscContentList = QString(stream.readAll()).split('\n');
                    f.close();
                    for (int i = 0; i < ProcMiscContentList.size(); ++i) {
                        QString line = ProcMiscContentList.at(i);
                        if (line.contains("tun", Qt::CaseInsensitive)) {
                            tunsupportfound = true;
                            break;
                        }
                    }
                }

                if (tunsupportfound) {
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("Support for TUN/TAP found (compiled into kernel or kernel module already loaded)."), KVpncEnum::debug);
                } else {
                    if (!Utils(GlobalConfig, parent).loadKernelModule("tun", parent)) {
                        KMessageBox::information(this, i18n("Loading of module \"%1\" failed." , QString("tun")));
                        GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, loading module \"%1\" has failed: stop." , QString("tun")), KVpncEnum::error);
                        disconnectClicked();
                        setGuiStatus(KVpncEnum::disconnected);
                        GlobalConfig->status = KVpncEnum::disconnected;
                        return ;
                    } else {
                        if (GlobalConfig->KvpncDebugLevel > 0)
                            GlobalConfig->appendLogEntry(i18n("Loading of module \"%1\" was successful." , QString("tun")), KVpncEnum::debug);
                    }
                }
            }

            if (GlobalConfig->KvpncDebugLevel > 3)
                GlobalConfig->appendLogEntry(i18n("Generating vpnc config"), KVpncEnum::debug);

            vpncConfig = "";
            vpncConfig += "IPSec gateway " + GlobalConfig->TmpGatewayIP + "\n";
            vpncConfig += "IPSec ID " + GlobalConfig->currentProfile->getID() + "\n";
            QString GrpPassStr = "";
            GrpPassStr = GlobalConfig->TmpGroupPassword;
// 				if (GlobalConfig->KvpncDebugLevel > 5)
// 					GlobalConfig->appendLogEntry(i18n("Group pass: %1" , GrpPassStr), KVpncEnum::debug);


            //vpncConfig += "IPSec secret " + GrpPassStr + "\n";
            vpncConfig += "Xauth username " + GlobalConfig->TmpUsername + "\n";

            //if ((vpnc_version_minor == 3 && vpnc_version_minor >= 2) || (vpnc_version_minor > 3))
            //    vpncConfig += "Xauth password " + GlobalConfig->TmpPassword + "\n";

            if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk )
            {

            }
            else if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert )
            {

            }
            else if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::hybrid )
            {
                vpncConfig += QString("IKE Authmode")+ QString(" ") + QString("hybrid") + QString("\n");
                if ( !GlobalConfig->currentProfile->getCaCertificate().isEmpty() ) {
                    vpncConfig += QString( "CA-File " + GlobalConfig->currentProfile->getCaCertificate() + "\n");
                }
                if ( !GlobalConfig->currentProfile->getCertPath().isEmpty() ) {
                    vpncConfig += QString("CA-Dir " + GlobalConfig->currentProfile->getCertPath() + "\n");
                }
            }



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

            QString VpncConfigFile = tmpPath + "vpnc-config." + GlobalConfig->currentProfile->getName(); // vpnc-config.<name>

            // FIXME maybe this as config option?
            bool force_vpnc_config_file = true;

            if ((vpnc_version_major <= 0 && vpnc_version_minor <= 3 && vpnc_version_subminor <= 2) || force_vpnc_config_file ) {
                // write vpnc connect script
                if (GlobalConfig->KvpncDebugLevel > 1)
                    GlobalConfig->appendLogEntry("VpncConfig: " + VpncConfigFile + "\n", KVpncEnum::debug);
                QFile configfile(VpncConfigFile);
                QTextStream configstream(&configfile);
                if (configfile.open(QIODevice::WriteOnly)) {
                    configstream << vpncConfig << "\n";
                    configfile.close();
                } else {
                    KMessageBox::information(this, i18n("Failed to create \"%1\"." , VpncConfigFile));
                    GlobalConfig->appendLogEntry(i18n("Failed to create \"%1\"." , VpncConfigFile), KVpncEnum::error);
                    disconnectClicked();
                    setGuiStatus(KVpncEnum::disconnected);
                    GlobalConfig->status = KVpncEnum::disconnected;
                    return ;
                }

            }

            VpncProcess = new KPtyProcess;
            VpncPty = VpncProcess->pty();
            VpncProcess->setOutputChannelMode(KProcess::MergedChannels);
            VpncProcess->setPtyChannels(KPtyProcess::AllChannels);
            VpncProcess->setUseUtmp(true);
            VpncProcess->setEnvironment(*env);
            connect(VpncProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutputFrom_vpnc()));
            connect(VpncProcess, SIGNAL(readyReadStandardError()), this, SLOT(readOutputFrom_vpnc()));
            connect(VpncProcess, SIGNAL(started()), this, SLOT(vpncStarted()));
            connect(VpncPty, SIGNAL(readyRead()), this, SLOT(readFromPty_vpnc()));

            QString proc = GlobalConfig->pathToVpnc;
            QStringList args;
            args.append("--script");
            args.append(VpncScript);

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


            if (GlobalConfig->VpncDebugLevel > 0) {

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

            //if ((vpnc_version_minor == 3 && vpnc_version_subminor >= 3) || (vpnc_version_minor >= 3 && vpnc_version_minor >= 3 && //vpnc_version_subminor >= 3))
            //    args.append("--non-inter");

            if (GlobalConfig->currentProfile->getUseNtDomainName()) {
                args.append("--domain");
                args.append(GlobalConfig->currentProfile->getNtDomainName());
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Using (NT) domain name \"%1\"." , GlobalConfig->currentProfile->getNtDomainName()), KVpncEnum::debug);
            }

            if (GlobalConfig->currentProfile->getUseNat() && GlobalConfig->currentProfile->getCiscoNatMode() != "none") {
                if (vpnc_version_major >= 0 && vpnc_version_minor >= 4) {
                    // TODO add other nat modes
                    args.append("--natt-mode");
                    args.append(GlobalConfig->currentProfile->getCiscoNatMode());
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("Using NAT-T mode \"%1\"." , GlobalConfig->currentProfile->getCiscoNatMode()), KVpncEnum::debug);
                } else
                    args.append("--udp");

                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Using UDP."), KVpncEnum::debug);
            } else {
                if ((vpnc_version_major == 0 && vpnc_version_minor >= 4) || (vpnc_version_major >= 1)) {
                    args.append("--natt-mode");
                    args.append("none");
                } else {
                    args.append("--disable-natt");
                }
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Disabling NAT-T."), KVpncEnum::debug);
            }

            if (GlobalConfig->currentProfile->getUseLocalPort() == true) {
                args.append("--local-port");
                args.append(QString().setNum(GlobalConfig->currentProfile->getLocalPort()));
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Using user-defined local port \"%1\"." , QString().setNum(GlobalConfig->currentProfile->getLocalPort())), KVpncEnum::debug);
            }


            if (GlobalConfig->currentProfile->getUseUdpPort()) {
                args.append("--udp-port");
                args.append(QString().setNum(GlobalConfig->currentProfile->getUdpPort()));
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Using user-defined UDP port \"%1\"." , GlobalConfig->currentProfile->getUdpPort()), KVpncEnum::debug);
            }


            if (GlobalConfig->currentProfile->getUseXauthInteractive() && ((vpnc_version_minor == 3 && vpnc_version_minor >= 2) || (vpnc_version_minor > 3))) {
                args.append("--xauth-inter");
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Enabling interactive extended authentication (for challenge response auth)"), KVpncEnum::debug);
            }

            if (GlobalConfig->currentProfile->getUseApplicationVersion()) {
                args.append("--application-version");
                args.append(GlobalConfig->currentProfile->getApplicationVersion());
                GlobalConfig->appendLogEntry(i18n("Using user-defined application version \"%1\"." , GlobalConfig->currentProfile->getApplicationVersion()) , KVpncEnum::debug);
            }


            //      else
            //      {
            //       args.append( "--local-port");
            //       args.append( "0"); // random port
            //       GlobalConfig->appendLogEntry ( i18n( "Using random port." ), KVpncEnum::info);
            //      }


            if (GlobalConfig->currentProfile->getUsePerfectForwardSecrety() && !GlobalConfig->currentProfile->getPerfectForwardSecrety().isEmpty()) {
                args.append("--pfs");
                args.append(GlobalConfig->currentProfile->getPerfectForwardSecrety());
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Using user-defined PFS \"%1\"." , GlobalConfig->currentProfile->getPerfectForwardSecrety()), KVpncEnum::debug);
            }

            if (GlobalConfig->currentProfile->getUseIkeGroup() && !GlobalConfig->currentProfile->getIkeGroup().isEmpty()) {
                args.append("--dh");
                args.append(GlobalConfig->currentProfile->getIkeGroup());
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Using user-defined IKE group \"%1\"." , GlobalConfig->currentProfile->getIkeGroup()), KVpncEnum::debug);
            }

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

            if (vpnc_version_major >= 0 && vpnc_version_minor >= 4) {
                args.append("--ifmode");
                if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tap") {
                    if (GlobalConfig->KvpncDebugLevel > 1)
                        GlobalConfig->appendLogEntry(i18n("Using tunnel device type: %1." , QString("TAP")), KVpncEnum::debug);
                    args.append("tap");
                } else {
                    if (GlobalConfig->KvpncDebugLevel > 1)
                        GlobalConfig->appendLogEntry(i18n("Using tunnel device type: %1." , QString("TUN")), KVpncEnum::debug);
                    args.append("tun");
                }
            }
            if (GlobalConfig->currentProfile->getDisableDataEncryption() == true) {
                if (vpnc_version_major >= 0 && vpnc_version_minor >= 5) {
                    args.append("--enable-no-encryption");
                }
            }


            args.append(QString("--gateway"));
            args.append(GlobalConfig->TmpGatewayIP);
            //
            //     args.append(QString("--username"));
            //     args.append(GlobalConfig->TmpUsername);
            //
            args.append(QString("--id"));
            args.append(GlobalConfig->currentProfile->getID());

            args.append(QString("--no-detach"));

            if ((vpnc_version_major == 0 && vpnc_version_minor >= 5) || (vpnc_version_major > 0)) {
                if (GlobalConfig->currentProfile->getUseDpdIdleTimeout()) {
                    args.append("--dpd-idle");
                    args.append(QString().setNum(GlobalConfig->currentProfile->getDpdIdleTimeout()));
                    if (GlobalConfig->KvpncDebugLevel > 1)
                        GlobalConfig->appendLogEntry(i18n("Using DPD idle timeout: %1." , GlobalConfig->currentProfile->getDpdIdleTimeout()), KVpncEnum::debug);
                } else {
                    // disabling DPD (Dead Peer Detection)
                    args.append("--dpd-idle");
                    args.append("0");
                    if (GlobalConfig->KvpncDebugLevel > 1)
                        GlobalConfig->appendLogEntry(i18n("Disabling DPD idle timeout."), KVpncEnum::debug);
                }
            }

            if (vpnc_version_major <= 0 && vpnc_version_minor <= 3 && vpnc_version_subminor <= 2) {
                //      args.append("--gateway");
                //      args.append(GlobalConfig->TmpGatewayIP);
                //      args.append("--id");
                //      args.append(GlobalConfig->currentProfile->getID());
                args.append(VpncConfigFile);
            }
            else {
                if (force_vpnc_config_file) {
                    if (GlobalConfig->KvpncDebugLevel > 5)
                        GlobalConfig->appendLogEntry(i18n("Forcing vpnc config in real file: \"%1\"." , VpncConfigFile), KVpncEnum::debug);
                    args.append(VpncConfigFile);
                } else {
                    if (vpnc_version_minor > 3) {
                        // we send config via stdin
                        args.append("-");
                    } else {
                        if (vpnc_version_subminor > 2) {
                            // we send config via stdin
                            args.append("-");
                        }
                    }
                }
            }


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

            if (GlobalConfig->currentProfile->getUseDnsUpdate()) {
                setenv("DNS_UPDATE", "Yes", 1);
                *env << "DNS_UPDATE=Yes";
            } else {
                setenv("DNS_UPDATE", "NO", 1);
                *env << "DNS_UPDATE=NO";
            }

            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Setting DNS_UPDATE \"%1\"." , QString(qgetenv("DNS_UPDATE"))), KVpncEnum::debug);

            if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() ) {
                if ( GlobalConfig->KvpncDebugLevel > 3 )
                    GlobalConfig->appendLogEntry ( i18n ( "Replacing default route: %1", i18n ( "yes" ) ), KVpncEnum::debug );
            } else {
                if ( GlobalConfig->KvpncDebugLevel > 3 )
                    GlobalConfig->appendLogEntry ( i18n ( "Replacing default route: %1", i18n ( "no" ) ), KVpncEnum::debug );
            }

            if (GlobalConfig->KvpncDebugLevel > 1) {
                GlobalConfig->appendLogEntry(i18n("vpnc: %1" , proc), KVpncEnum::debug);
                GlobalConfig->appendLogEntry(i18n("vpnc arguments: %1" , args.join(" ")), KVpncEnum::debug);
            }
            sendingVpncConfigInProgress = false;
            if (GlobalConfig->KvpncDebugLevel > 3)
                GlobalConfig->appendLogEntry(i18n("Starting %1 process.", i18n("vpnc")), KVpncEnum::debug);
            VpncProcess->setProgram(proc, args);
            VpncProcess->setEnvironment(*env);
            VpncProcess->start();

        } else {
            VpncScript = tmpPath + "vpnc-script." + GlobalConfig->currentProfile->getName(); // vpnc-script.<name>
            GlobalConfig->appendLogEntry(i18n("Making %1 (%2) executable failed." , QString("VpncScript") , VpncScript), KVpncEnum::error);
            setGuiStatus(KVpncEnum::disconnected);
            timer.stop();
            return ;
        }
    } // vpnc

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

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


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


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

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

            if (AuthRetry)
                askUsernamePass = true;

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

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

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

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

            } else {
                if (GlobalConfig->KvpncDebugLevel > 4)
                    GlobalConfig->appendLogEntry(i18n("User data already collected."), KVpncEnum::debug);
            }

            if (GlobalConfig->currentProfile->getAskUserPasswordOnEachConnect()) {
                if (GlobalConfig->KvpncDebugLevel > 4)
                    GlobalConfig->appendLogEntry(i18n("User password on each connect forced."), KVpncEnum::debug);

                askUsernamePass = true;
            }

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

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

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

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

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

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

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

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

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


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

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

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

                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("Some account data which was needed was obtained from a password dialog."), KVpncEnum::debug);

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


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

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

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


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

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

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

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

            //   QString tunneldevice = "tun0";
            OldDefaultroute = tmpPath + "default-route." + GlobalConfig->currentProfile->getName(); // default-route.<id>

            QFile DefaultRouteBackupFile(OldDefaultroute + ".sh");
            QTextStream DefaultRouteBackupFileStream(&DefaultRouteBackupFile);
            if (DefaultRouteBackupFile.open(QIODevice::WriteOnly)) {
                DefaultRouteBackupFileStream << "# generated by kvpnc. Do not edit it." << "\n";
                DefaultRouteBackupFileStream << "\n";
                DefaultRouteBackupFileStream << GlobalConfig->pathToIp + " route show | grep default > " + OldDefaultroute + "\n";
                DefaultRouteBackupFile.close();
                QProcess backupDefaultRouteProcess(this);
                QString proc = GlobalConfig->InterpreterShell;
                QStringList args;
                args.append(OldDefaultroute + ".sh");
                backupDefaultRouteProcess.setEnvironment(*env);
                backupDefaultRouteProcess.start(proc, args);
                if (!backupDefaultRouteProcess.waitForStarted()) {
                    //     if ( GlobalConfig->KvpncDebugLevel > 0 )
                    GlobalConfig->appendLogEntry(i18n("Connect canceled because default route backup process could not be started."), KVpncEnum::error);
                    return ;
                } else {
                    if (GlobalConfig->KvpncDebugLevel > 2)
                        GlobalConfig->appendLogEntry(i18n("Default route backup process started."), KVpncEnum::debug);
                }
            } else {
                //    if ( GlobalConfig->KvpncDebugLevel > 0 )
                GlobalConfig->appendLogEntry(i18n("Connect canceled because a backup of the default route could not be created."), KVpncEnum::error);
                return ;
            }

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

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

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

            CiscoVpncProcess = new KProcess(this);
            CiscoVpncProcess->setOutputChannelMode(KProcess::MergedChannels);
            CiscoVpncProcess->setEnvironment(*env);

            connect(CiscoVpncProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutputFrom_ciscovpnc()));

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

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


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

                if ( GlobalConfig->currentProfile->getUseNat() )
                {
                    stream << "EnableNat=1" << "\n";
                    if ( GlobalConfig->currentProfile->getUseNat() )
                        stream << "TunnelingMode=0" << "\n";
                    else
                    {
                        stream << "TunnelingMode=1" << "\n";
                        if ( GlobalConfig->currentProfile->getUseLocalPort())
                            stream << "TcpTunnelingPort=" << GlobalConfig->currentProfile->getLocalPort() << "\n";
                    }
                }
                else
                {
                    stream << "EnableNat=0" << "\n";
                }


                if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert )
                {
                    if ( GlobalConfig->currentProfile->getUseCiscoCertStore() )
                    {
                        stream << "CertStore=1" << "\n";
                    }
                    else
                    {
                        stream << "CertStore=0" << "\n";
                    }
                    stream << "CertPath=" << GlobalConfig->currentProfile->getCertPath() << "\n";
                    stream << "CertName=" << GlobalConfig->currentProfile->getX509Certificate() << "\n";

                    //stream << "CertSubjectName=" << "\n";
                    //stream << "CertSerialHash=00000000000000000000000000000000" << "\n";
                    stream << "SendCertChain=0" << "\n";
                }


                stream << "PeerTimeout=" << GlobalConfig->currentProfile->getDpdIdleTimeout() << "\n";
                stream << "EnableLocalLAN=0" << "\n"; // always off

                file.close();

                QString proc = GlobalConfig->pathToCiscoVpnc;
                QStringList args;

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

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

                setenv("DNS_UPDATE", (GlobalConfig->currentProfile->getUseDnsUpdate() ? "Yes" : "NO"), 1);

                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Setting DNS_UPDATE \"%1\"." , QString(qgetenv("DNS_UPDATE"))), KVpncEnum::debug);

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

//     connect ( ConnectProcess, SIGNAL ( processExited () ), this, SLOT ( vpncStarted() ) );
//     connect ( ConnectProcess, SIGNAL ( wroteToStdin() ), this, SLOT ( wroteToStdin_vpncConfig() ) );

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

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

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

        //setGuiStatus(connecting);
        // looking for racoon
        if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon)
            if (Utils(GlobalConfig).getToolInfo("racoon")->found == false) {
                KMessageBox::error(this, i18n("Unable to find \"%1\" at \"%2\"." , QString("racoon") , GlobalConfig->pathToRacoon));
                GlobalConfig->appendLogEntry(i18n("Unable to find \"%1\" at \"%2\"." , QString("racoon") , GlobalConfig->pathToRacoon), KVpncEnum::error);
                ok = false;
                setGuiStatus(KVpncEnum::disconnected);
                return ;
            }

        if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon) {
            if (Utils(GlobalConfig).getToolInfo("l2tpd")->found == false && Utils(GlobalConfig).getToolInfo("xl2tpd")->found == false) {
                KMessageBox::error(this, i18n("Unable to find \"%1\" or \"%2\"." , QString("l2tpd") , QString("xl2tpd")));
                GlobalConfig->appendLogEntry(i18n("Unable to find \"%1\" or \"%2\"." , QString("l2tpd") , QString("xl2tpd")), KVpncEnum::error);
                ok = false;
                setGuiStatus(KVpncEnum::disconnected);
                return ;
            }
        }

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

        QString resolvedIp = Utils ( GlobalConfig, parent ).resolveName ( GlobalConfig->currentProfile->getGateway() );
        if ( resolvedIp == "0.0.0.0" || resolvedIp.isEmpty() ) {
            KMessageBox::error(this, i18n("Host \"%1\" could not be resolved." , GlobalConfig->currentProfile->getGateway()));
            GlobalConfig->appendLogEntry(i18n("Host \"%1\" could not be resolved." , GlobalConfig->currentProfile->getGateway()), KVpncEnum::error) ;
            ok = false;
            setGuiStatus (KVpncEnum::disconnected);
            return;
        } else {
            GlobalConfig->TmpGatewayIP = resolvedIp;
            GlobalConfig->appendLogEntry(i18n("Gateway hostname (%1) resolved to \"%2\"." , GlobalConfig->currentProfile->getGateway() , GlobalConfig->TmpGatewayIP), KVpncEnum::info);
        }

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

        RacoonProcess = 0L;
        RacoonctlProcess = 0L;

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

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


        if (ok == false)
            return;

        bool askUsernamePass = false;
        bool askPsk = false;

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

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

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

                if (!GlobalConfig->currentProfile->getPskIsInFile())
                    GlobalConfig->TmpGroupPassword = GlobalConfig->currentProfile->getPreSharedKey();
                else {
                    QFile PskFile(GlobalConfig->currentProfile->getPreSharedKeyFile());
                    if (PskFile.open(QIODevice::ReadOnly)) {
                        QString PskFileContent = QString(PskFile.readAll());
                        PskFile.close();
                        GlobalConfig->TmpGroupPassword = PskFileContent;
                    }
                }
                GlobalConfig->WaitingForXauth = false;
                GlobalConfig->haveUserData = true;
            } else {
                if (GlobalConfig->KvpncDebugLevel > 4)
                    GlobalConfig->appendLogEntry(i18n("User data already collected."), KVpncEnum::debug);
            }
        }

        if (AuthRetry)
            askUsernamePass = true;

        if (GlobalConfig->currentProfile->getAskUserPasswordOnEachConnect()) {
            if (GlobalConfig->KvpncDebugLevel > 4)
                GlobalConfig->appendLogEntry(i18n("User password on each connect forced."), KVpncEnum::debug);

            askUsernamePass = true;
        }

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

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

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

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

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

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

                if (askPsk || AuthRetry) {

                    if (GlobalConfig->currentProfile->getPreSharedKey().isEmpty() || GlobalConfig->TmpGroupPassword.isEmpty()) {
                        GlobalConfig->appendLogEntry(i18n("PSK is empty."), KVpncEnum::error);
                        ok = false;
                    }
                }
                bool needSave = false;
                if (dlg.SaveUsernameCheckBox->isChecked()) {
                    GlobalConfig->currentProfile->setDontSaveUsername(false);
                    GlobalConfig->currentProfile->setUserName(dlg.UsernameEdit->text());
                    needSave = true;
                } else {
                    GlobalConfig->TmpUsername = dlg.UsernameEdit->text();
                    GlobalConfig->currentProfile->setDontSaveUsername(true);
                    needSave = true;
                }


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

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

                if (ok) {
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("Some account data which was needed was obtained from a password dialog."), KVpncEnum::debug);
                }
            } else {
                ok = false;
                AuthRetry = false;
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Connect canceled because account data dialog aborted."), KVpncEnum::debug);
            }
        }
        if (GlobalConfig->currentProfile->getPskIsInFile()) {
            QFile f(GlobalConfig->currentProfile->getPreSharedKeyFile());
            if (f.open(QIODevice::ReadOnly)) {
                QStringList contentlist = QString(f.readAll()).split("\n");
                for (int i = 0; i < contentlist.size(); ++i) {
                    QString line = contentlist.at(i);
                    if (!line.indexOf('#', 0) < 0) {
                        GlobalConfig->TmpGroupPassword = line;
                        break;
                    }
                }
                f.close();
            } else {
                GlobalConfig->appendLogEntry(i18n("PSK could not read from file because PSK key file %1 could not be read." , GlobalConfig->currentProfile->getPreSharedKeyFile()), KVpncEnum::error);
                ok = false;
            }
            if (GlobalConfig->TmpGroupPassword.isEmpty()) {
                GlobalConfig->appendLogEntry(i18n("PSK could not read from file because PSK key file %1 contains no key." , GlobalConfig->currentProfile->getPreSharedKeyFile()), KVpncEnum::error);
                ok = false;
            }
        }
        // here we go
        if (ok) {
            if (GlobalConfig->currentProfile->getExecuteCmdBeforeConnect())
                executeCommandBeforeConnect();

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

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

            // FIXME
            // if not virtual ip, its same as LocalIP
            QString VirtualLocalIP=LocalIP;
            // if not virtual ip, its 32 (only one host)
            QString VirtualLocalNetmask="32";

            if ( GlobalConfig->currentProfile->getUseLeftSourceIp() )
            {
                VirtualLocalIP = GlobalConfig->currentProfile->getLeftSourceIp();
            }

            if (GlobalConfig->KvpncDebugLevel > 0) {
                GlobalConfig->appendLogEntry(i18n("Default interface: %1", tmpInterface), KVpncEnum::debug);
                GlobalConfig->appendLogEntry(i18n("Local IP address: %1", LocalIP), KVpncEnum::debug);
                GlobalConfig->appendLogEntry(i18n( "Local IP address (virtual): %1", VirtualLocalIP ), KVpncEnum::debug );
                GlobalConfig->appendLogEntry(i18n( "Local netmask (virtual): %1", VirtualLocalNetmask ), KVpncEnum::debug );

            }

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

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

            // write setkey.conf
            QFile file(tmpPath + "setkey." + ProfileName + ".conf");
            QTextStream stream(&file);
            if (file.open(QIODevice::WriteOnly)) {

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

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

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

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

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

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

                    if (GlobalConfig->currentProfile->getUseRemoteNetwork()) {
                        stream << "spdadd " + VirtualLocalIP + " " + RemoteNet + " any -P out ipsec esp/tunnel/" + LocalIP + "-" + GlobalConfig->TmpGatewayIP + "/require;" << "\n";
                        stream << "spdadd " + RemoteNet + " " + VirtualLocalIP + " any -P in ipsec esp/tunnel/" + GlobalConfig->TmpGatewayIP + "-" + LocalIP + "/require;" << "\n";
                    } else {
                        stream << "spdadd " + LocalIP + " " + GlobalConfig->TmpGatewayIP + " any -P out ipsec esp/transport//require;" << "\n";
                        stream << "spdadd " + GlobalConfig->TmpGatewayIP + " " + LocalIP + " any -P in ipsec esp/transport//require;" << "\n";
                    }

                }


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

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

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

                        for (QStringList::Iterator it = AdditionalNetworkRoutes.begin(); it != AdditionalNetworkRoutes.end(); ++it) {
                            QString net = (*it).section('#', 0, 0);
                            //        stream << "spdadd " + LocalIP + " " + net + " any -P out ipsec esp/tunnel/" + PolicyLocal + "-" + PolicyRemote + "/require;" << "\n";
                            //        stream << "spdadd " + net + " " + LocalIP + " any -P in ipsec esp/tunnel/" + PolicyRemote + "-" + PolicyLocal + "/require;" << "\n";
                            stream << "spdadd " + LocalIP + " " + net + " any -P out ipsec esp/tunnel/" + LocalIP + "-" + GlobalConfig->TmpGatewayIP + "/require;" << "\n";
                            stream << "spdadd " + net + " " + LocalIP + " any -P in ipsec esp/tunnel/" + GlobalConfig->TmpGatewayIP + "-" + LocalIP + "/require;" << "\n";
                        }
                    }
                }
            }
            file.close();

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

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

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

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

                //stream << "#option of controlling racoon by racoonctl tool is enabled" << "\n";
                stream << "listen {" << "\n";
                stream << " adminsock \"/var/run/racoon/racoon.sock\" \"root\" \"operator\" 0660;" << "\n";

                if ( GlobalConfig->currentProfile->getUseNat() ) {
                    stream << "  isakmp_natt " << LocalIP << " [4500];" << "\n";
                }
                //else {
                stream << "  isakmp " << LocalIP << " [500];" << "\n";
                //}
                stream << "}" << "\n";

                // 				if ( GlobalConfig->currentProfile->getUseNat() ) {
                // 					stream << "" << "\n";
                // 					stream << "timer" << "\n";
                // 					stream << "{" << "\n";
                //
                // 					//FIXME make it dynamiclly
                // 					stream << "  natt_keepalive 20 sec;" << "\n";
                // 					stream << "}" << "\n";
                // 				}
                stream << "" << "\n";
                stream << "remote " << GlobalConfig->TmpGatewayIP << " {" << "\n";
                stream << "  exchange_mode " << GlobalConfig->currentProfile->getExchangeMode() << ";" << "\n";

                if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert) {
                    stream << "  certificate_type x509 \"" << GlobalConfig->currentProfile->getX509Certificate() << "\" \"" << GlobalConfig->currentProfile->getX509Certificate() + "\";" << "\n";
                    if (!GlobalConfig->currentProfile->getCaCertificate().isEmpty())
                        stream << "  ca_type x509 \"" << GlobalConfig->currentProfile->getCaCertificate() << "\";" << "\n";

                    // FIXME make it dynamiclly
                    stream << "  proposal_check obey;" << "\n";

                    if (GlobalConfig->currentProfile->getVerifyCaCert())
                        stream << "  verify_cert on;" << "\n";
                    else
                        stream << "  verify_cert off;" << "\n";
                }

                if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::hybrid) {
                    if (!GlobalConfig->currentProfile->getCaCertificate().isEmpty())
                        stream << "  ca_type x509 \"" << GlobalConfig->currentProfile->getCaCertificate() << "\";" << "\n";

                    // FIXME make it dynamiclly
                    stream << "  proposal_check obey;" << "\n";

                    if (GlobalConfig->currentProfile->getVerifyCaCert())
                        stream << "  verify_cert on;" << "\n";
                    else
                        stream << "  verify_cert off;" << "\n";
                }

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

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

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

                stream << "  passive off;" << "\n";

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

                /*
                none:		No ID
                address:		The type is the IP address. This is the default type if you do not specify an identifier to use
                user_fqdn:	The type is a USER_FQDN (user fully-qualified domain name)
                fqdn:		The type is a FQDN (fully-qualified domain name)
                keyid (file):	The type is a KEY_ID, read from the file
                keyid:		The type is a KEY_ID, specified in the quoted string
                asn1dn:		The type is an ASN.1 distinguished name. If empty, DN from the Subject field in the certificate will be used
                */

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

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

                QString LocalIDType = GlobalConfig->currentProfile->getLocalIDType();
                if ( LocalIDType == "none" ) {
                    // no ID
                } else if ( LocalIDType == "address" ) {
                    if ( !GlobalConfig->currentProfile->getSpecialLocalID().isEmpty() )
                        stream << "  my_identifier address \"" << GlobalConfig->currentProfile->getSpecialLocalID() << "\";" << "\n";
                    else
                        stream << "  my_identifier address;" << "\n";
                } else if ( LocalIDType == "user_fqdn" ) {
                    stream << "  my_identifier user_fqdn \"" << GlobalConfig->currentProfile->getSpecialLocalID() << "\";" << "\n";
                } else if ( LocalIDType == "fqdn" ) {
                    stream << "  my_identifier fqdn \"" << GlobalConfig->currentProfile->getSpecialLocalID() << "\";" << "\n";
                } else if ( LocalIDType == "keyid (file)" ) {
                    stream << "  peers_identifier keyid tag " << GlobalConfig->currentProfile->getSpecialLocalID() << ";" << "\n";
                } else if ( LocalIDType == "keyid" ) {
                    stream << "  my_identifier keyid \"" << GlobalConfig->currentProfile->getSpecialLocalID() << "\";" << "\n";
                } else if ( LocalIDType == "asn1dn" ) {
                    stream << "  my_identifier asn1dn;" << "\n";
                }


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

                // FIXME: make dynamiclly
                stream << "    proposal_check obey;" << "\n";

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

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

                if (! GlobalConfig->currentProfile->getHashAlgo().isEmpty())
                    stream << "    hash_algorithm " << GlobalConfig->currentProfile->getHashAlgo() << ";" << "\n";

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

                /*
                modp768		1
                modp1024	2
                modp1536	5
                modp2048	14
                modp3072	15
                modp4096	16
                modp6144	17
                modp8192	18
                */
                QString DhGroupNumber = "2";
                if (GlobalConfig->currentProfile->getIkeGroup() == "modp768")
                    DhGroupNumber = "1";
                else if (GlobalConfig->currentProfile->getIkeGroup() == "modp1024")
                    DhGroupNumber = "2";
                else if (GlobalConfig->currentProfile->getIkeGroup() == "modp1536")
                    DhGroupNumber = "5";
                else if (GlobalConfig->currentProfile->getIkeGroup() == "modp2048")
                    DhGroupNumber = "14";
                else if (GlobalConfig->currentProfile->getIkeGroup() == "modp3072")
                    DhGroupNumber = "15";
                else if (GlobalConfig->currentProfile->getIkeGroup() == "modp4096")
                    DhGroupNumber = "16";
                else if (GlobalConfig->currentProfile->getIkeGroup() == "modp6144")
                    DhGroupNumber = "17";
                else if (GlobalConfig->currentProfile->getIkeGroup() == "modp8192")
                    DhGroupNumber = "18";

                stream << "    dh_group " + DhGroupNumber + ";" << "\n";

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

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


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

                // FIXME make dynamiclly
                stream << "  lifetime time 1 hour;" << "\n";

                if (GlobalConfig->currentProfile->getUsePerfectForwardSecrety()) {
                    QString pfs_group = "";
                    // 					if ( GlobalConfig->currentProfile->getPerfectForwardSecrety() == "server" )
                    // 						pfs_group = "";
                    // 					else if ( GlobalConfig->currentProfile->getPerfectForwardSecrety() == "nopfs" )
                    // 						pfs_group = "";
                    // 					else if ( GlobalConfig->currentProfile->getPerfectForwardSecrety() == "dh1" )
                    // 						pfs_group = "1";
                    // 					else if ( GlobalConfig->currentProfile->getPerfectForwardSecrety() == "dh2" )
                    // 						pfs_group = "2";
                    // 					else if ( GlobalConfig->currentProfile->getPerfectForwardSecrety() == "dh5" )
                    // 						pfs_group = "5";

                    pfs_group = GlobalConfig->currentProfile->getPerfectForwardSecrety();

                    QString PFSGroupNumber = "2";
                    if (pfs_group== "modp768")
                        PFSGroupNumber = "1";
                    else if (pfs_group== "modp1024")
                        PFSGroupNumber = "2";
                    else if (pfs_group== "modp1536")
                        PFSGroupNumber = "5";
                    else if (pfs_group== "modp2048")
                        PFSGroupNumber = "14";
                    else if (pfs_group== "modp3072")
                        PFSGroupNumber = "15";
                    else if (pfs_group== "modp4096")
                        PFSGroupNumber = "16";
                    else if (pfs_group== "modp6144")
                        PFSGroupNumber = "17";
                    else if (pfs_group== "modp8192")
                        PFSGroupNumber = "18";
                    if ( !pfs_group.isEmpty() )
                        stream << "  pfs_group " << PFSGroupNumber << ";\n";
                } else {
                    // racoon allows to empty this if no pfs is requested
                    //stream << "  pfs_group modp768;" << "\n";
                }

                stream << "  encryption_algorithm " << GlobalConfig->currentProfile->getEncryptionAlgorithm() << ";" << "\n";
                //if ( GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())
                stream << "  authentication_algorithm " << GlobalConfig->currentProfile->getAuthenticationAlgorithm() << ";" << "\n";
                //else
                //	stream << "  authentication_algorithm " << GlobalConfig->currentProfile->getAuthenticationAlgorithm() << ", non_auth;" << "\n";



// 				Utils::IpsecAlgos KernelCrypto = Utils ( GlobalConfig ).getKernelCrypto();
// 				// phase 2 encr algos from kernel
// 				QString EncrAlgos="";
// 				for ( QStringList::Iterator it = KernelCrypto.IpsecEspEncryptionAlgorithms.begin(); it != KernelCrypto.IpsecEspEncryptionAlgorithms.end(); ++it )
// 				{
// 				if (EncrAlgos.length() > 0)
// 				EncrAlgos+=",";
// 				EncrAlgos+= QString(*it );
// 				}
//
//
// 				// phase 2 auth algos from kernel
// 				QString AuthAlgos="";
// 				for ( QStringList::Iterator it = KernelCrypto.IpsecEspAuthenticationAlgorithms.begin(); it != KernelCrypto.IpsecEspAuthenticationAlgorithms.end(); ++it )
// 				{
// 				if (AuthAlgos.length() > 0)
// 				AuthAlgos+=",";
// 				AuthAlgos+= QString(*it );
// 				}
//
//
// 				stream << "  encryption_algorithm " << EncrAlgos << ";"<<"\n";
// 				stream << "  authentication_algorithm " << AuthAlgos << ";"<< "\n";


                stream << "  compression_algorithm deflate;" << "\n";
                stream << "}" << "\n";

                //     stream << "listen {" << "\n";
                //
                //     //FIXME make own port useable
                //     stream << "  isakmp " << LocalIP << ";" << "\n";
                //     if ( GlobalConfig->currentProfile->getUseNat() )
                //     {
                //      if ( GlobalConfig->currentProfile->getUseUdpPort() )
                //      {
                //       stream << "  # isakmp port for nat-t" << "\n";
                //       stream << "  isakmp_natt " << LocalIP << "["<< GlobalConfig->currentProfile->getUdpPort() << "];" << "\n";
                //      }
                //      else
                //      {
                //       stream << "  isakmp_natt " << LocalIP << ";" << "\n";
                //      }
                //     }
                //     stream << "}" << "\n";
                file.close();
                stream.setDevice(0);
            }

            // write setkey.<profile>.sh
            file.setFileName(tmpPath + "setkey." + ProfileName + ".sh");
            stream.setDevice(&file);
            if (file.open(QIODevice::WriteOnly)) {
                stream <<  "#!" << GlobalConfig->InterpreterShell << "\n";
                stream << "# generated by kvpnc. Do not edit it." << "\n";
                stream << "# profile: " + ProfileName << "\n";
                stream << "" << "\n";
                stream << "# run setkey" << "\n";
                stream << GlobalConfig->pathToSetkey << " -f " << tmpPath + "setkey." + GlobalConfig->currentProfile->getName() + ".conf" << "\n";
                file.close();
                stream.setDevice(0);
            }


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

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

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

                if (GlobalConfig->currentProfile->getUseNat()) {
                    stream << "" << "\n";
                    stream << "#  NAT-T" << "\n";
                    stream << GlobalConfig->pathToIptables << " -I INPUT -p udp --dport 4500 -i " << tmpInterface2 << " -s " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
                    stream << GlobalConfig->pathToIptables << " -I OUTPUT -p udp --sport 4500 -i " << tmpInterface2 << " -d " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
                }
                if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon) {
                    stream << "" << "\n";
                    stream << "#  L2TP" << "\n";
                    stream << GlobalConfig->pathToIptables << " -I INPUT -p udp --dport 1701 -i " << tmpInterface2 << " -s " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
                    stream << GlobalConfig->pathToIptables << " -I OUTPUT -p udp --sport 1701 -i " << tmpInterface2 << " -d " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
                }
                file.close();
            } else {
                GlobalConfig->appendLogEntry(i18n("\"%1\" write failed.", QString(file.fileName())), KVpncEnum::error);
                setGuiStatus(KVpncEnum::disconnected);
                return;
            }

            stream.setDevice(0);

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

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

                if (GlobalConfig->currentProfile->getUseNat()) {
                    stream1 << "" << "\n";
                    stream1 << "#  NAT-T" << "\n";
                    stream1 << GlobalConfig->pathToIptables << " -D INPUT -p udp --dport 4500 -i " << tmpInterface2 << " -s " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
                    stream1 << GlobalConfig->pathToIptables << " -D OUTPUT -p udp --sport 4500 -i " << tmpInterface2 << " -d " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
                }
                if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon) {
                    stream1 << "" << "\n";
                    stream1 << "#  L2TP" << "\n";
                    stream1 << GlobalConfig->pathToIptables << " -D INPUT -p udp --dport 1701 -i " << tmpInterface2 << " -s " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
                    stream1 << GlobalConfig->pathToIptables << " -D OUTPUT -p udp --sport 1701 -i " << tmpInterface2 << " -d " << GlobalConfig->TmpGatewayIP << " -j ACCEPT" << "\n";
                }
                file1.close();
            } else {
                GlobalConfig->appendLogEntry(i18n("\"%1\" write failed." , QString(file1.fileName())), KVpncEnum::error);
                setGuiStatus(KVpncEnum::disconnected);
                return;
            }


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


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

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

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

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

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

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

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

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

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

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

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

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


                }

                upfile.close();
            } else {
                GlobalConfig->appendLogEntry(i18n("\"%1\" write failed." , QString(upfile.fileName())), KVpncEnum::error);
                setGuiStatus(KVpncEnum::disconnected);
                return;
            }


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

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

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

                    // deleting internal IP address from virtual network interface
                    downstream << "ip address delete ${INTERNAL_ADDR4} dev ${if}" << "\n";
                }

                // deleting route towards VPN gateway" << "\n";
                downstream << "ip route delete ${REMOTE_ADDR} via " << GlobalConfig->TmpGatewayIP << "" << "\n";

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

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

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

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


                downfile.close();
            } else {
                GlobalConfig->appendLogEntry(i18n("\"%1\" write failed.", QString(downfile.fileName())), KVpncEnum::error);
                setGuiStatus(KVpncEnum::disconnected);
                return;
            }

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

            if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk) {
                // write iptables.<profile>.sh
                file.setFileName(tmpPath + "psk." + ProfileName + ".key");
                stream.setDevice(&file);
                if (file.open(QIODevice::WriteOnly)) {
                    stream << "# generated by kvpnc. Do not edit it." << "\n";
                    stream << "# profile: " + ProfileName << "\n";

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

                file.close();
                stream.setDevice(0);
            }

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

            setenv("DNS_UPDATE", (GlobalConfig->currentProfile->getUseDnsUpdate() ? "Yes" : "NO"), 1);

            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Setting DNS_UPDATE \"%1\"." , QString(qgetenv("DNS_UPDATE"))), KVpncEnum::debug);

            if (useL2tpAfterFirstConnection)
                prepareL2tpd();

            Utils(GlobalConfig).doChmod(tmpPath + "psk." + GlobalConfig->currentProfile->getName() + ".key", "go-rwx");

            OpenL2tpProcess = 0L;
            L2tpdProcess = 0L;

            RacoonHelperProcess = new QProcess;
            //
            QString proc = GlobalConfig->InterpreterShell;
            QStringList args;
            args.append(tmpPath + "/setkey." + GlobalConfig->currentProfile->getName() + ".sh");

            connect(RacoonHelperProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_racoon_helper()));
            connect(RacoonHelperProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_racoon_helper()));
            connect(RacoonHelperProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(doRacoon(int, QProcess::ExitStatus)));

            RacoonHelperProcess->setEnvironment(*env);
            RacoonHelperProcess->start(proc, args);
            if (!RacoonHelperProcess->waitForStarted()) {
                disconnect(RacoonHelperProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_racoon_helper()));
                disconnect(RacoonHelperProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_racoon_helper()));
                disconnect(RacoonHelperProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(doRacoon(int, QProcess::ExitStatus)));
                delete RacoonHelperProcess;
                RacoonHelperProcess = 0L;
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("setkey")), KVpncEnum::error);
                KMessageBox::error(this, i18n("Failed to start \"%1\"." , QString("setkey." + GlobalConfig->currentProfile->getName() + ".sh")));
                setGuiStatus(KVpncEnum::disconnected);
            } else {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString("setkey")), KVpncEnum::debug);
                if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon)
                    ConnectingProcess = VpnAccountData::racoon;
                else
                    ConnectingProcess = VpnAccountData::l2tpd_racoon;
                GlobalConfig->status = KVpncEnum::connecting;
                mw->buttonDisconnect->setEnabled(true);
                this->DisconnectAction->setEnabled(true);
                mw->buttonConnect->setEnabled(false);
                this->ConnectAction->setEnabled(false);

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

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

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

        //setGuiStatus(connecting);

        // looking for ipsec

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


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

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

            QFile CertTmpFile;
            CertTmpFile.setFileName(GlobalConfig->currentProfile->getCaCertificate());
            if (!CertTmpFile.exists()) {
                KMessageBox::error(0, i18n("CA certificate file (%1) could not be found. Please check its path." , GlobalConfig->currentProfile->getCaCertificate()), i18n("File Not Found"));
                GlobalConfig->appendLogEntry(i18n("CA certificate file (%1) could not be found. Please check its path." , GlobalConfig->currentProfile->getCaCertificate()), KVpncEnum::error);
                ok = false;
            }
        }

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




        bool askUsernamePass = false;
        bool askPsk = false;

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

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

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

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



        if (AuthRetry)
            askUsernamePass = true;

        if (GlobalConfig->currentProfile->getAskUserPasswordOnEachConnect()) {
            if (GlobalConfig->KvpncDebugLevel > 4)
                GlobalConfig->appendLogEntry(i18n("User password on each connect forced."), KVpncEnum::debug);

            askUsernamePass = true;
        }

        if (!GlobalConfig->haveUserData) {

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

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

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

                if (!GlobalConfig->TmpPassword.isEmpty()) {
                    dlg.PasswordEdit->setText(GlobalConfig->TmpPassword);
                    if (GlobalConfig->currentProfile->getSaveUserPassword())
                        dlg.SaveUsernameCheckBox->setChecked(true);
                } else if (!GlobalConfig->TmpUsername.isEmpty())
                    dlg.PasswordEdit->setFocus();
            } else {
                GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();
                GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserName();
            }
            if (askPsk) {
                if (!GlobalConfig->currentProfile->getPreSharedKey().isEmpty()) {
                    dlg.PSKLineEdit->setText(GlobalConfig->currentProfile->getPreSharedKey());
                    if (GlobalConfig->currentProfile->getSavePsk())
                        dlg.SavePskCheckBox->setChecked(true);
                } else if (!GlobalConfig->currentProfile->getUserPassword().isEmpty())
                    dlg.PSKLineEdit->setFocus();
                if (!askUsernamePass) {
                    dlg.PasswordEdit->hide();
                    dlg.UsernameEdit->hide();
                    dlg.LabelPassword->hide();
                    dlg.LabelUsername->hide();
                    dlg.SavePasswordCheckBox->hide();
                    dlg.SaveUsernameCheckBox->hide();
                } else {
                    GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();
                    GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserName();
                }
            } else {
                dlg.LabelGroupPassword->hide();
                dlg.PSKLineEdit->hide();
            }

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

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

                // FIXME
                if (askPsk || AuthRetry) {
                    if ((GlobalConfig->currentProfile->getSavePsk() && GlobalConfig->currentProfile->getPreSharedKey().isEmpty()) && GlobalConfig->TmpGroupPassword.isEmpty()) {
                        GlobalConfig->appendLogEntry(i18n("PSK is empty."), KVpncEnum::error);
                        ok = false;
                    }
                }

                bool needSave = false;

                if (askUsernamePass) {
                    if (dlg.SavePasswordCheckBox->isChecked()) {
                        GlobalConfig->currentProfile->setSaveUserPassword(true);
                        GlobalConfig->currentProfile->setUserPassword(GlobalConfig->TmpPassword);
                        needSave = true;
                    } else {
                        GlobalConfig->currentProfile->setSaveUserPassword(false);
                        needSave = true;
                    }
                }
                if (askPsk) {
                    if (dlg.SavePskCheckBox->isChecked()) {
                        GlobalConfig->currentProfile->setSavePsk(true);

                        if (!GlobalConfig->currentProfile->getPskIsInFile()) {
                            GlobalConfig->currentProfile->setPreSharedKey(GlobalConfig->TmpGroupPassword);
                            needSave = true;
                        }
                        else {
                            QFile PskFile(GlobalConfig->currentProfile->getPreSharedKeyFile());
                            if (PskFile.open(QIODevice::WriteOnly)) {
                                QTextStream stream(&PskFile);
                                stream << GlobalConfig->TmpGroupPassword;
                                PskFile.close();
                            }
                        }

                    } else {
                        GlobalConfig->currentProfile->setSavePsk(false);
                        needSave = true;
                    }
                }

                if (needSave)
                    GlobalConfig->saveOptions(true, GlobalConfig->currentProfile->getName());

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

                if (ok) {
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("Some account data which was needed was obtained from a password dialog."), KVpncEnum::debug);
                    //      saveSessionClicked();
                }
                GlobalConfig->haveUserData = true;
            } else {
                ok = false;
                AuthRetry = false;
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Connect canceled because account data dialog aborted."), KVpncEnum::debug);
            }
        }


        if (GlobalConfig->currentProfile->getPskIsInFile()) {
            QFile f(GlobalConfig->currentProfile->getPreSharedKeyFile());
            if (f.open(QIODevice::ReadOnly)) {
                QStringList contentlist = QString(f.readAll()).split("\n");
                for (int i = 0; i < contentlist.size(); ++i) {
                    QString line = contentlist.at(i);
                    if (!line.indexOf(QChar('#'), 0, Qt::CaseInsensitive) < 0) {
                        GlobalConfig->TmpGroupPassword = line;
                        break;
                    }
                }
                f.close();
            } else {
                GlobalConfig->appendLogEntry(i18n("PSK could not read from file because PSK key file %1 could not be read." , GlobalConfig->currentProfile->getPreSharedKeyFile()), KVpncEnum::error);
                ok = false;
            }
            if (GlobalConfig->TmpGroupPassword.isEmpty()) {
                GlobalConfig->appendLogEntry(i18n("PSK could not read from file because PSK key file %1 contains no key." , GlobalConfig->currentProfile->getPreSharedKeyFile()), KVpncEnum::error);
                ok = false;
            }
        }

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

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

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

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

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


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

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

            backupDefaultRoute();

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

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

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

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

            QString Gateway = GlobalConfig->currentProfile->getGateway();
            QString RemoteNetAddr = GlobalConfig->currentProfile->getRemoteNetAddr();
            QString RemoteNetMask = GlobalConfig->currentProfile->getRemoteNetMask();
            QString RemoteNet = "";
            if (!RemoteNetAddr.isEmpty())
                RemoteNet = RemoteNetAddr + "/" + RemoteNetMask;
            QString LocalNetAddr = LocalIP;
            QString LocalNetMask = "/32";
            QString LocalNet = "";

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

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

            startStopIpsec(true);
            backupIpsecSystemConfig();

            QString IpsecPrefix = "/etc";

            // write /etc/ipsec.secrets
            QFile IpsecSecretsFile(IpsecPrefix + "/ipsec.secrets");    // warning: static
            QTextStream stream(&IpsecSecretsFile);
            if (IpsecSecretsFile.open(QIODevice::WriteOnly)) {
                // cert
                if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert) {
                    stream << "# generated by kvpnc. Do not edit it." << "\n";
                    stream << "# profile: " + ProfileName << "\n";
                    if (!GlobalConfig->currentProfile->getUseSmartcard())
                        stream << ": RSA " + GlobalConfig->currentProfile->getPrivateKey() + " \"" + GlobalConfig->currentProfile->getPrivateKeyPass() + "\"\n";
                    else {
                        stream << ": PIN %smartcard \"" << Pkcs11PIN << "\"" << "\n";
                        //       stream << ": PIN %smartcard \"123456\"" << "\n";
                        //       stream << ": PIN %smartcard %prompt" << "\n";

                    }

                    //  mw->DebugOutput->append( "cert: private key: : RSA " + PrivateKey + " \"" + PrivateKeyPass );
                }
                // PSK
                else {
                    stream << "# generated by kvpnc. Do not edit it." << "\n";
                    stream << "# profile: " + ProfileName << "\n";

                    if (!GlobalConfig->currentProfile->getPskIsInFile()) {
                        GlobalConfig->appendLogEntry ( QString("ipsec: "+ IpsecToolInfo->Version ), KVpncEnum::debug );
                        if ( !GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() )
                        {
                            //if ( !GlobalConfig->currentProfile->getUseSpecialLocalID())
                            //	stream << "" << GlobalConfig->TmpGatewayIP  << " : PSK \"" + GlobalConfig->currentProfile->getPreSharedKey() + "\"\n";
                            //else
                            stream << "" << GlobalConfig->TmpGatewayIP  << " " << GlobalConfig->currentProfile->getSpecialLocalID() << " : PSK \"" + GlobalConfig->currentProfile->getPreSharedKey() + "\"\n";
                        } else if ((IpsecToolInfo->Version.contains("Openswan", Qt::CaseInsensitive) && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())) {
                            // XAUTH openswan
                            stream << GlobalConfig->TmpGatewayIP  << " @" << GlobalConfig->currentProfile->getID() << "  : PSK \"" + GlobalConfig->currentProfile->getPreSharedKey() + "\"\n";
                        } else if ((IpsecToolInfo->Version.contains("strongSwan", Qt::CaseInsensitive) && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())) {
                            // XAUTH strongSwan
                            stream << ": PSK \"" + GlobalConfig->currentProfile->getPreSharedKey() + "\"\n";
                            stream << ": XAUTH \"" + GlobalConfig->TmpUsername + "\" \"" + GlobalConfig->TmpPassword + "\"" + "\n";
                        }
                    } else {
                        QFile PskFile(GlobalConfig->currentProfile->getPreSharedKeyFile());
                        if (PskFile.open(QIODevice::ReadOnly)) {
                            QString PskFileContent = QString(PskFile.readAll());
                            PskFile.close();
                            if (!GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()) {
                                // normal
                                stream << ": PSK \"" + PskFileContent + "\"\n";
                            } else {
                                // XAUTH
                                stream << GlobalConfig->TmpGatewayIP  << " @" << GlobalConfig->currentProfile->getID() << "  : PSK \"" + PskFileContent + "\"\n";
                            }
                        }
                    }

                }
                IpsecSecretsFile.close();

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

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

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

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

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

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

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

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

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


                    stream << "    klipsdebug=\"";
                    for ( QStringList::Iterator it = GlobalConfig->KlipsDebug.begin(); it != GlobalConfig->KlipsDebug.end(); ++it )
                    {
                        stream << *it << " ";

                    }
                    if (GlobalConfig->KlipsDebug.isEmpty())
                        stream << "none";
                    stream << "\"" << "\n";

                    stream << "    plutodebug=\"";
                    for ( QStringList::Iterator it = GlobalConfig->PlutoDebug.begin(); it != GlobalConfig->PlutoDebug.end(); ++it )
                    {
                        stream << *it << " ";

                    }
                    if (GlobalConfig->PlutoDebug.isEmpty())
                        stream << "none";
                    stream << "\"" << "\n";


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

                    if (realversion.indexOf(QString("1."), 0, Qt::CaseInsensitive) > -1) {
                        if (!IpsecToolInfo->Version.contains("strongSwan", Qt::CaseInsensitive))
                            stream << "    plutoload=%search" << "\n";
                        if (!IpsecToolInfo->Version.contains("strongSwan", Qt::CaseInsensitive))
                            stream << "    plutostart=%search" << "\n";
                        if (IpsecToolInfo->Version.contains("strongSwan", Qt::CaseInsensitive))
                            stream << "    plutostart=yes" << "\n";
                    }
                    stream << "" << "\n";
                    stream << "conn %default" << "\n";
                    stream << "    keyingtries=" << GlobalConfig->currentProfile->getMaxConnectTries() << "\n";

                    // FIXME make it dynamiclly
                    stream << "    keylife=1200s" << "\n";
                    stream << "    ikelifetime=1200s" << "\n";
                    stream << "\n";

                    // our connection
                    stream << "conn " << GlobalConfig->currentProfile->getName() << "\n";
                    // x509
                    if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert) {
                        stream << "    authby=rsasig" << "\n";
                        stream << "    leftrsasigkey=%cert" << "\n";
                        stream << "    rightrsasigkey=%cert" << "\n";
                    } else if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk) {
                        // FIXME maybe we should store rightrsasigkey at better place
                        if (GlobalConfig->currentProfile->getUseSpecialServerCertificate())
                        {
                            stream << "    rightrsasigkey=" << GlobalConfig->currentProfile->getSpecialServerCertificate() << "\n";
                        }

                        // FIXME maybe we should store leftrsasigkey at better place
                        if (GlobalConfig->currentProfile->getPskIsInFile())
                        {
                            stream << "    leftrsasigkey=" << GlobalConfig->currentProfile->getPreSharedKeyFile() << "\n";
                        }


                        if ( ( IpsecToolInfo->Version.contains ( "strongSwan", false ) && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() ) ) {
                            stream << "    authby=xauthpsk" << "\n";
                        } else {
                            stream << "    authby=secret" << "\n";
                        }
                    }
                    if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
                        stream << "    type=transport" << "\n"; // we have to use tunnel mode

                        if (GlobalConfig->currentProfile->getIpsecVpnMode() == "tunnel") {
                            GlobalConfig->currentProfile->setIpsecVpnMode("transport");
                            GlobalConfig->appendLogEntry(i18n("IPsec vpn mode was set to \"tunnel\" but must be \"transport\" for use with L2TP. This was temporarily fixed."), KVpncEnum::info);
                        }
                    } else {
                        stream << "    type=" << GlobalConfig->currentProfile->getIpsecVpnMode() << "\n";
                    }
                    if (GlobalConfig->currentProfile->getExchangeMode() == "aggressive") {
                        stream << "    aggrmode=yes" << "\n";
                    }

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

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

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

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

                    if ( GlobalConfig->currentProfile->getUsePerfectForwardSecrety() ) {
                        stream << "    pfs=yes" << "\n";
                        QString pfs_group = GlobalConfig->currentProfile->getPerfectForwardSecrety();

                        // 						QString PFSGroupNumber = "2";
                        // 						if (pfs_group== "modp768")
                        // 							PFSGroupNumber = "1";
                        // 						else if (pfs_group== "modp1024")
                        // 							PFSGroupNumber = "2";
                        // 						else if (pfs_group== "modp1536")
                        // 							PFSGroupNumber = "5";
                        // 						else if (pfs_group== "modp2048")
                        // 							PFSGroupNumber = "14";
                        // 						else if (pfs_group== "modp3072")
                        // 							PFSGroupNumber = "15";
                        // 						else if (pfs_group== "modp4096")
                        // 							PFSGroupNumber = "16";
                        // 						else if (pfs_group== "modp6144")
                        // 							PFSGroupNumber = "17";
                        // 						else if (pfs_group== "modp8192")
                        // 							PFSGroupNumber = "18";
                        if ( !pfs_group.isEmpty() )
                            // 							stream << "    pfsgroup=" << PFSGroupNumber << "\n";
                            stream << "    pfsgroup=" << pfs_group << "\n";
                    } else {
                        stream << "    pfs=no" << "\n";
                    }



//     stream << "    auto=start" << "\n";
                    stream << "    left=" + LocalIP << "\n"; // local ip
//     stream << "    left=%defaultroute" << "\n"; // iface to default route
                    //     stream << " leftnexthop = "+LocalNet << "\n";
                    //     stream << " leftsubnet = " << "\n"; // local network

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

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

                        if (GlobalConfig->currentProfile->getUseSpecialRemoteID())
                            stream << "    rightid=\"" + GlobalConfig->currentProfile->getSpecialRemoteID() << "\"" << "\n";
                        //stream << "    rightid=\"/C=DE/ST=Sachsen-Anhalt/O=Powersoft/OU=IT/CN=212.100.100.212\"" << "\n";
//      else
//      {
//       if ( GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert )
//        rightid = getX509CertificateID ( GlobalConfig->currentProfile->getX509Certificate(), false ); // remote
//      }

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

                    }
                    if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk) {
                        if (GlobalConfig->currentProfile->getUseSpecialRemoteID()) {
                            if ( GlobalConfig->currentProfile->getRemoteIDType() == "asn1dn" ) {
                                stream << "    rightid=@" << GlobalConfig->TmpGatewayIP << "\n";
                            }
                            else {
                                if (GlobalConfig->currentProfile->getRemoteIDType() == "address" && !Utils(GlobalConfig).isValidIPv4Address( GlobalConfig->currentProfile->getSpecialRemoteID() ) ) {
                                    QString resolvedIp = Utils(GlobalConfig).resolveName(GlobalConfig->currentProfile->getSpecialRemoteID());
                                    if (resolvedIp.isEmpty()) {
                                        GlobalConfig->appendLogEntry( i18n("Remote ID \"%1\" (type: address) could not resolved, ommiting right id.", GlobalConfig->currentProfile->getSpecialRemoteID()), KVpncEnum::error );

                                    } else {
                                        if (GlobalConfig->KvpncDebugLevel > 3)
                                            GlobalConfig->appendLogEntry( i18n("Remote ID \"%1\" (type: address) resolved to: %2", GlobalConfig->currentProfile->getSpecialRemoteID()).arg(resolvedIp), KVpncEnum::debug );
                                        stream << "    rightid=" + resolvedIp << "\n";
                                    }
                                }

                                else {
                                    stream << "    rightid=" + GlobalConfig->currentProfile->getSpecialRemoteID() << ""<< "\n";
                                }
                            }
                        }

                        //stream << "    rightid=\"/C=DE/ST=Sachsen-Anhalt/O=Powersoft/OU=IT/CN=212.100.100.212\"" << "\n";
                        //if (GlobalConfig->currentProfile->getUseSpecialLocalID() && !GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()) {
                        if (GlobalConfig->currentProfile->getUseSpecialLocalID()) {
                            if (GlobalConfig->currentProfile->getLocalIDType() == "asn1dn")
                                stream << "    leftid=" << GlobalConfig->TmpGatewayIP << "\n";
                            else
                            {
                                if (GlobalConfig->currentProfile->getLocalIDType() == "address" && !Utils(GlobalConfig).isValidIPv4Address( GlobalConfig->currentProfile->getSpecialLocalID() ) ) {
                                    QString resolvedIp = Utils(GlobalConfig).resolveName(GlobalConfig->currentProfile->getSpecialLocalID());
                                    if (resolvedIp.isEmpty()) {
                                        GlobalConfig->appendLogEntry( i18n("Local ID \"%1\" (type: address) could not resolved, ommiting left id.", GlobalConfig->currentProfile->getSpecialLocalID()), KVpncEnum::error );

                                    } else {
                                        if (GlobalConfig->KvpncDebugLevel > 3)
                                            GlobalConfig->appendLogEntry( i18n("Local ID \"%1\" (type: address) resolved to: %2", GlobalConfig->currentProfile->getSpecialLocalID()).arg(resolvedIp), KVpncEnum::debug );
                                        stream << "    leftid=" + resolvedIp << "\n";
                                    }
                                }

                                else
                                    stream << "    leftid=\"" + GlobalConfig->currentProfile->getSpecialLocalID() << "\""<< "\n";
                            }

                        }
                    }

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

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


                    if (GlobalConfig->currentProfile->getUseVirtualIP()) {
                        if (!GlobalConfig->currentProfile->getRemoteVirtualIP().isEmpty())
                            stream << "    rightsubnet=" << GlobalConfig->currentProfile->getRemoteVirtualIP() << "\n";
                    } else {
                        if (GlobalConfig->currentProfile->getUseRemoteNetwork() && !RemoteNetAddr.isEmpty())
                            stream << "    rightsubnet=" << RemoteNet << "\n";
                    }

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

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




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

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

                    stream << "    auto=add" << "\n";

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

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

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

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

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

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

                    IpsecConfigFile.close();
                    if (GlobalConfig->KvpncDebugLevel > 6) {
                        GlobalConfig->appendLogEntry(IpsecPrefix + "/ipsec.conf", KVpncEnum::debug);
                        GlobalConfig->appendLogEntry("---------------------", KVpncEnum::debug);
                        QString IpsecContent = "";
                        QFile file(IpsecPrefix + "/ipsec.conf");
                        if (file.open(QIODevice::ReadOnly)) {
                            QStringList contentlist = QString(file.readAll()).split("\n");
                            for (int i = 0; i < contentlist.size(); ++i) {
                                QString line = contentlist.at(i);
                                GlobalConfig->appendLogEntry(line, KVpncEnum::debug);
                            }
                            file.close();
                        }
                        GlobalConfig->appendLogEntry("---------------------", KVpncEnum::debug);
                    }
                } else {
                    GlobalConfig->appendLogEntry(i18n("%1 could not be opened. Stop.", IpsecConfigFile.fileName()), KVpncEnum::error);
                    setGuiStatus(KVpncEnum::disconnected);
                    return;
                }

                stream.setDevice(0);



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

                // write iptables.<profile>_add_ipsec_freeswan.sh
                QFile file(tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".add_ipsec_freeswan.sh");
                stream.setDevice(&file);
                if (file.open(QIODevice::WriteOnly)) {
                    stream <<  "#!" << GlobalConfig->InterpreterShell << "\n";
                    stream << "# generated by kvpnc. Do not edit it." << "\n";
                    stream << "# profile: " + ProfileName << "\n";
                    stream << "" << "\n";
                    stream << "#  AH" << "\n";
                    stream << GlobalConfig->pathToIptables << " -I INPUT -p 50 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
                    stream << GlobalConfig->pathToIptables << " -I OUTPUT -p 50 -d " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
                    stream << "" << "\n";
                    stream << "#  ESP" << "\n";
                    stream << GlobalConfig->pathToIptables << " -I INPUT -p 51 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
                    stream << GlobalConfig->pathToIptables << " -I OUTPUT -p 51 -d " << GlobalConfig->currentProfile->getGateway() << " -j  ACCEPT" << "\n";
                    stream << "" << "\n";
                    stream << "#  IKE" << "\n";
                    stream << GlobalConfig->pathToIptables << " -I INPUT -p udp --dport 500 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
                    stream << "" << "\n";
                    stream << "#  NAT-T" << "\n";
                    stream << GlobalConfig->pathToIptables << " -I INPUT -p udp --dport 4500 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
                    if (GlobalConfig->currentProfile != 0 && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
                        stream << "#  L2TP" << "\n";
                        stream << GlobalConfig->pathToIptables << " -I OUTPUT -p udp --sport 1701 -o " << tmpInterface2 << " -s " << LocalIP << " -j ACCEPT" << "\n";
                        stream << GlobalConfig->pathToIptables << " -I INPUT -p udp --dport 1701 -i " << tmpInterface2 << " -d " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
                    }
                    file.close();
                } else {
                    GlobalConfig->appendLogEntry(i18n("%1 could not be opened. Stop." , tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".add_ipsec_freeswan.sh"), KVpncEnum::error);
                    setGuiStatus(KVpncEnum::disconnected);
                    return;
                }
                stream.setDevice(0);

                QFile file1(tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".remove_ipsec_freeswan.sh");
                QTextStream stream1(&file1);
                if (file1.open(QIODevice::WriteOnly)) {
                    stream1 <<  "#!" << GlobalConfig->InterpreterShell << "\n";
                    stream1 << "# generated by kvpnc. Do not edit it." << "\n";
                    stream1 << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";
                    stream1 << "" << "\n";
                    stream1 << "#  AH" << "\n";
                    stream1 << GlobalConfig->pathToIptables << " -D INPUT -p 50 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
                    stream1 << GlobalConfig->pathToIptables << " -D OUTPUT -p 50 -d " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
                    stream1 << "" << "\n";
                    stream1 << "#  ESP" << "\n";
                    stream1 << GlobalConfig->pathToIptables << " -D INPUT -p 51 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
                    stream1 << GlobalConfig->pathToIptables << " -D OUTPUT -p 51 -d " << GlobalConfig->currentProfile->getGateway() << " -j  ACCEPT" << "\n";
                    stream1 << "" << "\n";
                    stream1 << "#  IKE" << "\n";
                    stream1 << GlobalConfig->pathToIptables << " -D INPUT -p udp --dport 500 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
                    stream1 << "" << "\n";
                    stream1 << "#  NAT-T" << "\n";
                    stream1 << GlobalConfig->pathToIptables << " -D INPUT -p udp --dport 4500 -i " << tmpInterface2 << " -s " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
                    if (GlobalConfig->currentProfile != 0 && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
                        stream1 << "#  L2TP" << "\n";
                        stream1 << GlobalConfig->pathToIptables << " -D OUTPUT -p udp --sport 1701 -o " << tmpInterface2 << " -s " << LocalIP << " -j ACCEPT" << "\n";
                        stream1 << GlobalConfig->pathToIptables << " -D INPUT -p udp --dport 1701 -i " << tmpInterface2 << " -d " << GlobalConfig->currentProfile->getGateway() << " -j ACCEPT" << "\n";
                    }

                } else {
                    GlobalConfig->appendLogEntry(i18n("%1 could not be opened. Stop." , tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".remove_ipsec_freeswan.sh"), KVpncEnum::error);
                    setGuiStatus(KVpncEnum::disconnected);
                    return;
                }

                if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk) {
                    // write psk.<profile>.key
                    QFile Pskfile(tmpPath + "psk." + ProfileName + ".key");
                    stream.setDevice(&Pskfile);
                    if (Pskfile.open(QIODevice::WriteOnly)) {
                        stream << GlobalConfig->currentProfile->getPreSharedKey() << "\n";
                        Pskfile.close();
                    } else {
                        GlobalConfig->appendLogEntry(i18n("%1 could not be opened. Stop.", Pskfile.fileName()), KVpncEnum::error);
                    }

                    stream.setDevice(0);
                }

                setenv("DNS_UPDATE", (GlobalConfig->currentProfile->getUseDnsUpdate() ? "Yes" : "NO"), 1);

                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Setting DNS_UPDATE \"%1\"." , QString(qgetenv("DNS_UPDATE"))), KVpncEnum::debug);

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



                if (useL2tpAfterFirstConnection)
                    prepareL2tpd();

                IpsecPhase1Up = false;
                IpsecPhase2Up = false;


//    startStopIpsec(false);
                OpenL2tpProcess = 0L;
                L2tpdProcess = 0L;
                IpsecStartProcess = 0L;

                IpsecStartProcess = new QProcess(this);
                QString proc = GlobalConfig->pathToIpsec;
                QStringList args;
                if (IpsecToolInfo->Version.contains("Openswan" , Qt::CaseInsensitive)) {

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

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


                    //args.append( "starter" );
                    //args.append ( "--nofork");
                    //QFile("/var/run/pluto.pid").remove();
                    //QFile("/var/run/starter.pid").remove();
                    //args.append( "setup" );
                    args.append("start");
                }

                IpsecGotError = false;

                connect(IpsecStartProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsec()));
                connect(IpsecStartProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsec()));
                connect ( IpsecStartProcess, SIGNAL ( finished (int, QProcess::ExitStatus) ), this, SLOT ( ipsecStarted(int, QProcess::ExitStatus) ) );

                IpsecStartProcess->setEnvironment(*env);
                IpsecStartProcess->start(proc, args);
                if (!IpsecStartProcess->waitForStarted()) {
                    KMessageBox::error(this, i18n("Failed to start \"%1\"." , QString("ipsec (" + IpsecType + "): setup")));
                    GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\".", QString("ipsec (" + IpsecType + "): setup")) , KVpncEnum::error);
                    disconnect(IpsecStartProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsec()));
                    disconnect(IpsecStartProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsec()));
                    disconnect ( IpsecStartProcess, SIGNAL ( finished (int, QProcess::ExitStatus) ), this, SLOT ( ipsecStarted(int, QProcess::ExitStatus) ) );
                    delete IpsecStartProcess;
                    IpsecStartProcess = 0L;
                    disconnectClicked();
                    setGuiStatus(KVpncEnum::disconnected);
                } else {

                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("IPsec daemon (%1) started.", QString(IpsecType)), KVpncEnum::debug);

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

                    GlobalConfig->currentConnectRetry++;

                    int currentConnectCounter = 0;
                    while (IpsecStartProcess && IpsecStartProcess->state() == QProcess::Running /*&& currentConnectCounter <= 500*/) {
                        if (GlobalConfig->KvpncDebugLevel > 8) {
                            if (IpsecToolInfo->Version.contains("strongSwan", Qt::CaseInsensitive))
                                GlobalConfig->appendLogEntry(i18n("\"%1\" still running, waiting", QString("ipsec start")) , KVpncEnum::debug);
                            else
                                GlobalConfig->appendLogEntry(i18n("\"%1\" still running, waiting", QString("ipsec setup start")) , KVpncEnum::debug);
                        }
                        currentConnectCounter++;
                        if (GlobalConfig->appPointer->hasPendingEvents())
                            GlobalConfig->appPointer->processEvents();
                        usleep(500);
                    }
                    disconnect(IpsecStartProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsec()));
                    disconnect(IpsecStartProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsec()));
                    disconnect(IpsecStartProcess, SIGNAL ( finished(int, QProcess::ExitStatus) ), this, SLOT ( ipsecStarted(int, QProcess::ExitStatus) ) );
                    delete IpsecStartProcess;
                    IpsecStartProcess = 0L;

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

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

        // looking for pppd
        if (Utils(GlobalConfig).getToolInfo(QString("pppd"))->found == false) {
            KMessageBox::error(this, i18n("Unable to find \"%1\" at \"%2\"." , QString("pppd") , GlobalConfig->pathToPppd));
            GlobalConfig->appendLogEntry(i18n("Unable to find \"%1\" at \"%2\"." , QString("pppd") , GlobalConfig->pathToPppd), KVpncEnum::error);
            ok = false;
            setGuiStatus(KVpncEnum::disconnected);
            return ;
        }
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("pppd: %1" , GlobalConfig->pathToPppd), KVpncEnum::debug);

        if ( GlobalConfig->KvpncDebugLevel > 3 )
            GlobalConfig->appendLogEntry ( i18n ( "Checking gre support" ), KVpncEnum::debug );
        bool gresupportfound = false;
        QString procnetdev = "";
        QFile f ( "/proc/net/dev" );
        if ( f.open ( IO_ReadOnly ) ) {
            QTextStream procnetdevstream ( &f );
            QString procnetdevcontent = QString(procnetdevstream.read());
            QStringList procnetdev_content_list = QStringList::split("\n", procnetdevcontent);
            QString line = "";
            for ( QStringList::Iterator it = procnetdev_content_list.begin(); it != procnetdev_content_list.end(); ++it ) {
                line = *it; // line of text excluding '\n'
                if ( line.contains ( "gre0", false ) ) {
                    gresupportfound = true;
                    break;
                }
            }
            f.close();
        }
        if ( !gresupportfound ) {
            QString procmodules = "";
            QFile f2 ( "/proc/modules" );
            if ( f2.open ( IO_ReadOnly ) ) {
                QTextStream procmodulesstream ( &f2 );
                QString procmodulescontent = QString(procmodulesstream.read());
                QStringList procmodules_content_list = QStringList::split("\n", procmodulescontent);
                QString line = "";
                for ( QStringList::Iterator it2 = procmodules_content_list.begin(); it2 != procmodules_content_list.end(); ++it2 ) {
                    line = *it2; // line of text excluding '\n'
                    if ( line.contains ( "ip_gre", false ) ) {
                        gresupportfound = true;
                        break;
                    }
                }
                f2.close();
            }
        }
        if ( gresupportfound ) {
            if ( GlobalConfig->KvpncDebugLevel > 0 )
                GlobalConfig->appendLogEntry ( i18n ( "Support for %1 found (compiled into kernel or kernel module already loaded).", QString("GRE")), KVpncEnum::debug );
        } else {
            if ( !Utils ( GlobalConfig, parent ).loadKernelModule ( "ip_gre", parent ) ) {
                KMessageBox::information ( this, i18n ( "Loading of module \"%1\" failed.", QString("ip_gre") ) );
                GlobalConfig->appendLogEntry ( i18n ( "Tunnel device is missing, loading module \"%1\" has failed: stop.", QString("ip_gre") ), KVpncEnum::error );
                disconnectClicked();
                setGuiStatus ( KVpncEnum::disconnected );
                GlobalConfig->status = KVpncEnum::disconnected;
                return ;
            } else {
                if ( GlobalConfig->KvpncDebugLevel > 0 )
                    GlobalConfig->appendLogEntry ( i18n ( "Loading of module \"%1\" was successful.", QString("ip_gre") ), KVpncEnum::debug );
            }
        }


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


        if (!pppdCapabilitiesCollected) {
            GlobalConfig->appPointer->setOverrideCursor(QCursor(Qt::WaitCursor));
            if (GlobalConfig->KvpncDebugLevel > 3)
                GlobalConfig->appendLogEntry(i18n("Collecting pppd capabilities..."), KVpncEnum::debug);
            GlobalConfig->pppdcap = Utils ( GlobalConfig ).checkPppdCapabilities();
            pppdCapabilitiesCollected = true;
            GlobalConfig->appPointer->restoreOverrideCursor();
        }
        pppdHasReplacedefaultrouteSupport = GlobalConfig->pppdcap.pppdHasReplacedefaultrouteSupport;

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

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



        if (GlobalConfig->currentProfile->getAskUserPasswordOnEachConnect()) {
            if (GlobalConfig->KvpncDebugLevel > 4)
                GlobalConfig->appendLogEntry(i18n("User password on each connect forced."), KVpncEnum::debug);

            askUsernamePass = true;
            requestUsername = true;
        }



        if (!GlobalConfig->haveUserData || GlobalConfig->currentProfile->getAskUserPasswordOnEachConnect()) {
            if (!GlobalConfig->currentProfile->getSaveUserPassword() || GlobalConfig->currentProfile->getUserPassword().isEmpty() || GlobalConfig->currentProfile->getUserName().isEmpty() || askUsernamePass) {


                EnterUsernamePasswordDialog dlg(this, i18n("Enter Account Data"), false, requestUsername);       // only password

                if (GlobalConfig->currentProfile->getSaveUserPassword()) {
                    //dlg.PasswordEdit->setText(GlobalConfig->currentProfile->getUserPassword());
                    dlg.SavePasswordCheckBox->setChecked(true);
                }
                if (AuthRetry)
                    dlg.UsernameEdit->setText ( GlobalConfig->TmpUsername );
                else
                    dlg.UsernameEdit->setText(GlobalConfig->currentProfile->getUserName());
                if (!dlg.UsernameEdit->text().isEmpty()) {                //go straight to pw if username present
                    dlg.PasswordEdit->setFocus();
                    if (!GlobalConfig->currentProfile->getDontSaveUsername())
                        dlg.SaveUsernameCheckBox->setChecked(true);
                }
                dlg.LabelID->hide();
                dlg.IDEdit->hide();


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

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

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

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

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


                    if (GlobalConfig->KvpncDebugLevel > 0 && ok)
                        GlobalConfig->appendLogEntry(i18n("Some passwords which were needed were obtained from a password dialog."), KVpncEnum::debug);
                } else {
                    ok = false;
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("Connect canceled because password enter dialog aborted."), KVpncEnum::debug);
                }
            } else {
                if (!GlobalConfig->currentProfile->getSaveUserPassword() || GlobalConfig->currentProfile->getUserPassword().isEmpty()) {
                    GlobalConfig->TmpPassword =  GlobalConfig->currentProfile->getUserPassword() ;
                }


                if (!GlobalConfig->currentProfile->getDontSaveUsername() || GlobalConfig->currentProfile->getUserName().isEmpty()) {                //go straight to pw if username present
                    GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();
                }
            }
        } else {
            if (GlobalConfig->KvpncDebugLevel > 4)
                GlobalConfig->appendLogEntry(i18n("User data already collected."), KVpncEnum::debug);
        }
        // here we go
        if (ok) {

            PppdDevice = "ppp0";
            if (GlobalConfig->currentProfile->getExecuteCmdBeforeConnect())
                executeCommandBeforeConnect();

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

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

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

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

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


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

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

            QFile file(PppdPeerScript);
            QTextStream stream(&file);
            if (file.open(QIODevice::WriteOnly)) {
                stream << "# generated by kvpnc. Do not edit it." << "\n";
                stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";
                stream << "" << "\n";
                stream << "\n";
                stream << "# name of tunnel, used to select lines in secrets files\n";
                stream << "remotename " + GlobalConfig->currentProfile->getName() + "\n";
                stream << "\n";
                stream << "# name of tunnel, used to name /var/run pid file\n";
                stream << "linkname kvpnc." + GlobalConfig->currentProfile->getName() + "\n";
                stream << "\n";
                stream << "# name of tunnel, passed to ip-up scripts\n";
                stream << "ipparam kvpnc." + GlobalConfig->currentProfile->getName() + "\n";
                stream << "\n";
                stream << "# data stream for pppd to use\n";
                QString pptpdebug = "";
                if (GlobalConfig->enableDebugPptpd == true) {
                    pptpdebug = " --debug ";
                    if (GlobalConfig->KvpncDebugLevel > 2)
                        GlobalConfig->appendLogEntry(i18n("Enabling debug for pptpd."), KVpncEnum::debug);
                }
                stream << "pty \"" << GlobalConfig->pathToPptp << " " << pptpdebug << "--loglevel " << QString().setNum(GlobalConfig->PptpLogLevel)  << " " << GlobalConfig->currentProfile->getGateway() << " --nolaunchpppd\"\n";
                stream << "\n";

                stream << "# domain and username, used to select lines in secrets files\n";
                if (GlobalConfig->currentProfile->getUseNtDomainName() && !GlobalConfig->currentProfile->getNtDomainName().isEmpty()) {
                    stream << "name \"" + GlobalConfig->currentProfile->getNtDomainName() + "\\\\" + GlobalConfig->currentProfile->getUserName() + "\"\n";
                    GlobalConfig->appendLogEntry(i18n("Using (NT) domain name \"%1\"." , GlobalConfig->currentProfile->getNtDomainName()), KVpncEnum::debug);
                } else
                    stream << "name \"" + GlobalConfig->currentProfile->getUserName() + "\"\n";
                stream << "\n";

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

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

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

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



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


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


                    stream << "\n";
                } else {
                    stream << "# disable MPPE encryption\n";
                    stream << GlobalConfig->pppdcap.RefuseMppeOption;
                    if (!GlobalConfig->pppdcap.MppeOptionsInALine)
                        stream << "\n";
                    stream << "\n";
                }

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

                if (GlobalConfig->enableDebugPppd) {
                    stream << "# enable debug\n";
                    stream << "debug\n";
                    stream << "\n";
                }

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

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

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

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

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


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

                if (GlobalConfig->currentProfile->getUseMru()) {
                    stream << "# userdefined MRU\n";
                    stream << "mru " + QString().setNum(GlobalConfig->currentProfile->getMru()) + "\n";
                    stream << "\n";
                } else {
                    stream << "# default MRU\n";
                    stream << "mru 1500" << "\n";
                    stream << "\n";
                }

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

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

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

                if (GlobalConfig->currentProfile->getDisableHeaderCompression()) {
                    stream << "# disable TCP header compression\n";
                    stream << "novj\n";
                    stream << "\n";
                }

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

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

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

                if (GlobalConfig->currentProfile->getDisableAddressControlCompression()) {
                    stream << "# disable address control compression\n";
                    stream << "noaccomp\n";
                    stream << "\n";
                }

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

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


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


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

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

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

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

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


                    stream << "\n";

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

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

                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1", QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                    file.setFileName(ChapSecrets);
                    stream.setDevice(&file);
                    if (file.open(QIODevice::WriteOnly | QIODevice::Append)) {
                        stream << "# +++ generated by kvpnc. Do not edit it." << "\n";
                        stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";

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

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

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

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


                        Utils(GlobalConfig, this).doChmod("/etc/ppp/chap-secrets", "go-rwx");
                    }
                }
                if (GlobalConfig->currentProfile->getAuthMethod() == "pap") {

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


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

                    stream << "# use pap" << "\n";
                    stream << GlobalConfig->pppdcap.RequireAuthPapOption << "\n";


                    // write pppd /etc/ppp/pap-secrets
                    QString papSecrets = "/etc/ppp/pap-secrets"; // /etc/ppp/pap-secrets

                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1", QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
                    file.setFileName(papSecrets);
                    stream.setDevice(&file);
                    if (file.open(QIODevice::WriteOnly | QIODevice::Append)) {
                        stream << "# +++ generated by kvpnc. Do not edit it." << "\n";
                        stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";

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

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

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

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


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


                file.close();
                /*
                    if (GlobalConfig->currentProfile->getAuthMethod() != "chap" && GlobalConfig->currentProfile->getAuthMethod() != "chap")
                     GlobalConfig->currentProfile->setAuthMethod("chap");*/
                if (!pppdCapabilitiesCollected) {
                    GlobalConfig->appPointer->setOverrideCursor(QCursor(Qt::WaitCursor));
                    if (GlobalConfig->KvpncDebugLevel > 3)
                        GlobalConfig->appendLogEntry(i18n("Collecting pppd capabilities..."), KVpncEnum::debug);
                    GlobalConfig->pppdcap = Utils ( GlobalConfig ).checkPppdCapabilities();
                    pppdCapabilitiesCollected = true;
                    GlobalConfig->appPointer->restoreOverrideCursor();
                }
                pppdHasReplacedefaultrouteSupport = GlobalConfig->pppdcap.pppdHasReplacedefaultrouteSupport;


                QFile pppdbackupdefaultroutefile(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".backup_default_route.sh");
                QTextStream pppdbackupdefaultroutestream(&pppdbackupdefaultroutefile);
                if (pppdbackupdefaultroutefile.open(QIODevice::WriteOnly)) {
                    pppdbackupdefaultroutestream <<  "#!" << GlobalConfig->InterpreterShell << "\n";
                    pppdbackupdefaultroutestream << "# generated by kvpnc. Do not edit it." << "\n";
                    pppdbackupdefaultroutestream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
                    pppdbackupdefaultroutestream << GlobalConfig->pathToIp << " route show | grep default | head -n1 > " << OldDefaultroute << "\n";
                    pppdbackupdefaultroutefile.close();
                }



                QProcess backupDefaultRouteProcess(this);
                QString proc = GlobalConfig->InterpreterShell;
                QStringList args;
                args.append(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".backup_default_route.sh");
                backupDefaultRouteProcess.setEnvironment(*env);
                backupDefaultRouteProcess.start(proc, args);
                if (!backupDefaultRouteProcess.waitForStarted()) {
                    KMessageBox::sorry(this, i18n("\"%1\" (%2) start failed." , QString("PppdBackupDefaultRouteScript"), QString(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".backup_default_route.sh")));
                } else {
                    if (GlobalConfig->KvpncDebugLevel > 2)
                        GlobalConfig->appendLogEntry(i18n("\"%1\" (%2) started.", QString("PppdBackupDefaultRouteScript") , tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".backup_default_route.sh") , KVpncEnum::debug);
                    waitForFinished(&backupDefaultRouteProcess, 100);

                    if (GlobalConfig->KvpncDebugLevel > 2)
                        GlobalConfig->appendLogEntry(i18n("\"%1\" (%2) finished.", QString("PppdBackupDefaultRouteScript"), tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".up") , KVpncEnum::debug);
                }

                // load the module 'ppp_mppe'
                QFile modprobe_confFile("/etc/modprobe.conf");
                if (modprobe_confFile.exists()) {
                    QString modprobe_confFileContent = "";
                    bool ppp_compress_18_found = false;
                    if (modprobe_confFile.open(QIODevice::ReadOnly)) {
                        QStringList contentlist = QString(modprobe_confFile.readAll()).split("\n");
                        for (int i = 0; i < contentlist.size(); ++i) {
                            QString line = contentlist.at(i);
                            if (line.contains("ppp-compress-18", Qt::CaseInsensitive)) {
                                ppp_compress_18_found = true;
                                break;
                            }
                        }
                        modprobe_confFile.close();
                        if (!ppp_compress_18_found) {
                            if (!modprobe_confFile.open(QIODevice::WriteOnly | QIODevice::Append)) {
                                GlobalConfig->appendLogEntry(i18n("%1 cannot be opened for appending." , QString("/etc/modprobe.conf")) , KVpncEnum::error);
                            } else {

                                stream.setDevice(&modprobe_confFile);
                                if (!Utils(GlobalConfig, parent).loadKernelModule("ppp_mppe", parent)) {
                                    if (GlobalConfig->KvpncDebugLevel > 0)
                                        GlobalConfig->appendLogEntry(i18n("Loading module \"%1\" failed, adding \"ppp_mppe_mppc\" to %2." , QString("ppp_mppe") , QString("/etc/modprobe.conf")), KVpncEnum::debug);
                                    stream << "\n" << "# added by kvpnc, do not edit it.\n" << "alias ppp-compress-18 ppp_mppe_mppc\n";
                                } else {
                                    if (GlobalConfig->KvpncDebugLevel > 0)
                                        GlobalConfig->appendLogEntry(i18n("Loading module \"%1\" succeeded, adding \"ppp_mppe\" to %2." , QString("ppp_mppe") , QString("/etc/modprobe.conf")), KVpncEnum::debug);
                                    stream << "\n" << "# added by kvpnc, do not edit it.\n" << "alias ppp-compress-18 ppp_mppe\n";
                                }

                                modprobe_confFile.close();

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

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

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

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

                if (load_module_ok) {

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

                    args.append("call");
                    args.append(QString("kvpnc." + GlobalConfig->currentProfile->getName()));

                    //args.append( GlobalConfig->InterpreterShell );
                    //args.append( "/home/crissi/pppd.sh" );

                    connect(PptpProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_pptp()));
                    connect(PptpProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_pptp()));


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

                    setenv("DNS_UPDATE", (GlobalConfig->currentProfile->getUseDnsUpdate() ? "Yes" : "NO"), 1);

                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("Setting DNS_UPDATE \"%1\"." , QString(qgetenv("DNS_UPDATE"))), KVpncEnum::debug);

                    PptpProcess->setEnvironment(*env);
                    PptpProcess->start(proc, args);
                    if (!PptpProcess->waitForStarted()) {
                        disconnect(PptpProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_pptp()));
                        disconnect(PptpProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_pptp()));
                        KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , QString("pppd")));
                        GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("pppd")), KVpncEnum::error);
                        disconnectClicked();
                        setGuiStatus(KVpncEnum::disconnected);
                    } else {
                        if (GlobalConfig->KvpncDebugLevel > 0)
                            GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString("pppd")), KVpncEnum::debug);
                        ConnectingProcess = VpnAccountData::pptp;
                        GlobalConfig->status = KVpncEnum::connecting;
                        mw->buttonDisconnect->setEnabled(true);
                        this->DisconnectAction->setEnabled(true);
                        mw->buttonConnect->setEnabled(false);
                        this->ConnectAction->setEnabled(false);
                        //connect ( PptpProcess, SIGNAL( started (int, QProcess::ExitStatus) ), this, SLOT( pppdStarted(int, QProcess::ExitStatus) ) );

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

                        //connect ( PptpProcess, SIGNAL ( finished(int, QProcess::ExitStatus) ), this, SLOT ( pptpProcessExited(int, QProcess::ExitStatus) ) );

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

    } // pptp

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

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

        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("openvpn: %1" , GlobalConfig->pathToOpenvpn) , KVpncEnum::debug);

        {

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

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

                    if (GlobalConfig->currentProfile->getPkcs11Slot().isEmpty()) {
                        KMessageBox::error(this, i18n("Pkcs11 slot cannot be empty."));
                        GlobalConfig->appendLogEntry(i18n("Pkcs11 slot cannot be empty."), KVpncEnum::error);
                        ok = false;
                        setGuiStatus(KVpncEnum::disconnected);
                        return ;
                    }
                    if (GlobalConfig->currentProfile->getPkcs11Id().isEmpty()) {
                        KMessageBox::error(this, i18n("Pkcs11 id cannot be empty."));
                        GlobalConfig->appendLogEntry(i18n("Pkcs11 id cannot be empty."), KVpncEnum::error);
                        ok = false;
                        setGuiStatus(KVpncEnum::disconnected);
                        return ;
                    }
                    if (GlobalConfig->currentProfile->getUsePkcs11Providers() && GlobalConfig->currentProfile->getPkcs11Providers().isEmpty()) {
                        KMessageBox::error(this, i18n("Pkcs11 providers cannot be empty."));
                        GlobalConfig->appendLogEntry(i18n("Pkcs11 providers cannot be empty."), KVpncEnum::error);
                        ok = false;
                        setGuiStatus(KVpncEnum::disconnected);
                        return ;
                    }
                } else {
                    /* use cert on filesystem */
                    QFile CertTmpFile;
                    if (! GlobalConfig->currentProfile->getUseOnlyCaCertAndUserAuth()) {
                        CertTmpFile.setFileName(GlobalConfig->currentProfile->getX509Certificate());
                        if (!CertTmpFile.exists()) {
                            //     KMessageBox::error( 0, i18n( "Certificate file (%1) could not be found. Please check its path." , GlobalConfig->currentProfile->getX509Certificate() ), i18n( "File Not Found" ) );
                            //     GlobalConfig->appendLogEntry( i18n( "Certificate file (%1) could not be found. Please check its path." , GlobalConfig->currentProfile->getX509Certificate() ), KVpncEnum::error );
                            //     ok = false;
                            //     setGuiStatus( disconnected );
                            //     return ;
                        } else {
                            CertTmpFile.setFileName(GlobalConfig->currentProfile->getPrivateKey());
                            if (!CertTmpFile.exists()) {
                                KMessageBox::error(0, i18n("Private key file (%1) could not be found. Please check its path." , GlobalConfig->currentProfile->getPrivateKey()), i18n("File Not Found"));
                                GlobalConfig->appendLogEntry(i18n("Private key file (%1) could not be found. Please check its path." , GlobalConfig->currentProfile->getPrivateKey()) , KVpncEnum::error);
                                ok = false;
                                setGuiStatus(KVpncEnum::disconnected);
                                return ;
                            }
                        }
                    } // only if real certificate

                    CertTmpFile.setFileName(GlobalConfig->currentProfile->getCaCertificate());
                    if (!CertTmpFile.exists()) {
                        KMessageBox::error(0, i18n("CA certificate file (%1) could not be found. Please check its path." , GlobalConfig->currentProfile->getCaCertificate()), i18n("File Not Found"));
                        GlobalConfig->appendLogEntry(i18n("CA certificate file (%1) could not be found. Please check its path." , GlobalConfig->currentProfile->getCaCertificate()) , KVpncEnum::error);
                        ok = false;
                        setGuiStatus(KVpncEnum::disconnected);
                        return ;
                    }
                }
            }

            bool tunsupportfound = false;
            QString procmisc = "";
            QFile f("/proc/misc");
            if (f.open(QIODevice::ReadOnly)) {
                QStringList contentlist = QString(f.readAll()).split("\n");
                for (int i = 0; i < contentlist.size(); ++i) {
                    QString line = contentlist.at(i);
                    if (line.contains("tun", Qt::CaseInsensitive)) {
                        tunsupportfound = true;
                        break;
                    }
                }
            }
            f.close();
            if (tunsupportfound) {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Support for TUN/TAP found (compiled into kernel or kernel module already loaded)."), KVpncEnum::debug);

                QFile tundevfile("/dev/net/tun");
                if (!tundevfile.exists()) {
                    if (!Utils(GlobalConfig, parent).createTunDev()) {
                        KMessageBox::error(this, i18n("Failed to create \"%1\"." , QString("/dev/net/tun")));
                        GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, creating it has failed: stop."), KVpncEnum::error);
                        disconnectClicked();
                        setGuiStatus(KVpncEnum::disconnected);
                        GlobalConfig->status = KVpncEnum::disconnected;
                        return ;
                    } else {
                        if (GlobalConfig->KvpncDebugLevel > 0)
                            GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, creating has been successful."), KVpncEnum::debug);
                    }
                }
            } else {
                // load the module 'tun'
                if (!Utils(GlobalConfig, parent).loadKernelModule("tun", parent)) {
                    KMessageBox::information(this, i18n("Loading of module \"%1\" failed." , QString("tun")));
                    GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, loading module \"%1\" has failed: stop." , QString("tun")), KVpncEnum::error);
                    disconnectClicked();
                    setGuiStatus(KVpncEnum::disconnected);
                    GlobalConfig->status = KVpncEnum::disconnected;
                    return ;
                } else {
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("Loading of module \"%1\" was successful." , QString("tun")), KVpncEnum::debug);
                }
            }

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

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


            if (!GlobalConfig->haveUserData) {
                if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()) {
                    if ( GlobalConfig->currentProfile->getSaveUserPassword() && GlobalConfig->currentProfile->getUserPassword().isEmpty()) {
                        askUsernamePass = true;
                        if ( GlobalConfig->KvpncDebugLevel > 3 )
                            GlobalConfig->appendLogEntry ( i18n ( "Empty user password" ), KVpncEnum::debug );
                    }
                    if ( !GlobalConfig->currentProfile->getSaveUserPassword() && GlobalConfig->TmpPassword.isEmpty()) {
                        askUsernamePass = true;
                        if ( GlobalConfig->KvpncDebugLevel > 3 )
                            GlobalConfig->appendLogEntry ( i18n ( "Empty tmp user password" ), KVpncEnum::debug );
                    }

                    if ( !GlobalConfig->currentProfile->getDontSaveUsername() ) {
                        requestUsername = GlobalConfig->currentProfile->getUserName().isEmpty();
                    } else {
                        requestUsername = GlobalConfig->TmpUsername.isEmpty();
                    }



                    if (AuthRetry) {
                        askUsernamePass = true;
                        requestUsername = true;
                    }
                }
                if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk) {
                    if (!GlobalConfig->currentProfile->getPskIsInFile() && GlobalConfig->currentProfile->getPreSharedKey().isEmpty())
                        askUsernamePass = true;
                    if ( GlobalConfig->KvpncDebugLevel > 3 )
                        GlobalConfig->appendLogEntry ( i18n ( "Psk is empty" ), KVpncEnum::debug );

                }
            }

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

            if (GlobalConfig->currentProfile->getAskUserPasswordOnEachConnect()) {
                if (GlobalConfig->KvpncDebugLevel > 4)
                    GlobalConfig->appendLogEntry(i18n("User password on each connect forced."), KVpncEnum::debug);

                askUsernamePass = true;
                requestUsername = true;
            }

            if (askUsernamePass) {

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

                EnterUsernamePasswordDialog dlg(this, i18n("Enter Account Data"), requestGrouppassword, requestUsername);
                dlg.SaveUsernameCheckBox->setChecked(!GlobalConfig->currentProfile->getDontSaveUsername());
                dlg.SavePasswordCheckBox->setChecked(GlobalConfig->currentProfile->getSaveUserPassword());

                if ((GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk && !GlobalConfig->currentProfile->getPskIsInFile() && GlobalConfig->currentProfile->getPreSharedKey().isEmpty()) && !GlobalConfig->currentProfile->getUseTlsAuth()) {
                    dlg.UsernameEdit->hide();
                    dlg.PasswordEdit->hide();

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

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

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

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

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

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


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

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

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


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

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

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

                }

                if (needSave)
                    GlobalConfig->saveOptions(true, GlobalConfig->currentProfile->getName());


                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Some passwords which were needed were obtained from a password dialog."), KVpncEnum::debug);

                AuthRetry = false;
                GlobalConfig->haveUserData = true;

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

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

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

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

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

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

                //if (GlobalConfig->KvpncDebugLevel > 0)
                //  {
                //     GlobalConfig->appendLogEntry( "debug: local virtual ip: "+GlobalConfig->currentProfile->getLocalVirtualIP(),KVpncEnum::debug );
                //     GlobalConfig->appendLogEntry( "debug: remote virtual ip: "+GlobalConfig->currentProfile->getRemoteVirtualIP(),KVpncEnum::debug );
                // }
                // write openvpn.<profile>.conf
                QFile openvpn_file(tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".conf");
                QTextStream openvpn_stream(&openvpn_file);
                if (openvpn_file.open(QIODevice::WriteOnly)) {
                    openvpn_stream << "# generated by kvpnc. Do not edit it." << "\n";
                    openvpn_stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
                    openvpn_stream << "# verbosity" << "\n";
                    openvpn_stream << "verb " << GlobalConfig->OpenvpnDebugLevel << "\n\n";

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

                    openvpn_stream << "# change to prefix" << "\n";
                    openvpn_stream << "cd " << certPath << "\n\n";

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

                    if (GlobalConfig->currentProfile->getDisableBind()) {
                        openvpn_stream << "# do not listen" << "\n";
                        openvpn_stream << "nobind" << "\n\n";
                    }

                    // openvpn > 2.1-rc9 we need script security parameter (http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=494998)
                    ToolInfo *OpenvpnToolInfo = Utils(GlobalConfig).getToolInfo("openvpn") ;
                    int OpenvpnMajor = OpenvpnToolInfo->Version.section(".", 0, 0).toInt();
                    int OpenvpnMinor = OpenvpnToolInfo->Version.section(".", 1, 1).section("_", 0, 0).toInt();
                    QString OpenvpnExtra = "";
                    int OpenvpnExtraVer = 0;
                    if (OpenvpnToolInfo->Version.section(".", 1, 1).indexOf(QChar('_'), 0, Qt::CaseInsensitive) > -1) {
                        if (OpenvpnToolInfo->Version.section(".", 1, 1).section("_", 1, 1).indexOf(QString("beta"), 0, Qt::CaseInsensitive) > -1) {
                            OpenvpnExtra = "beta";
                            OpenvpnExtraVer = OpenvpnToolInfo->Version.section(".", 1, 1).section("_", 1, 1).section("beta", 1, 1).toInt();
                        }
                        if (OpenvpnToolInfo->Version.section(".", 1, 1).section("_", 1, 1).indexOf(QString("rc"), 0, Qt::CaseInsensitive) > -1) {
                            OpenvpnExtra = "rc";
                            OpenvpnExtraVer = OpenvpnToolInfo->Version.section(".", 1, 1).section("_", 1, 1).section("rc", 1, 1).toInt();
                        }
                    }
                    if (GlobalConfig->KvpncDebugLevel > 4) {
                        GlobalConfig->appendLogEntry(i18n("OpenVPN major: %1, minor: %2, extra: %3, extra ver: %4", QString().setNum(OpenvpnMajor), QString().setNum(OpenvpnMinor), OpenvpnExtra, QString().setNum(OpenvpnExtraVer)), KVpncEnum::debug);
                    }


                    if (GlobalConfig->OpenvpnNeedSecurityParameter || (OpenvpnMajor == 2 && OpenvpnMinor == 1 && OpenvpnExtraVer > 8 && OpenvpnExtra == "rc")||  ( OpenvpnMajor == 2 && OpenvpnMinor == 1 ) || (OpenvpnMajor > 2 && OpenvpnMinor >= 2)) {
                        if (GlobalConfig->KvpncDebugLevel > 3)
                            GlobalConfig->appendLogEntry(i18n("OpenVPN >= 2.1-rc9 detected, adding script security parameter to config."), KVpncEnum::info);

                        openvpn_stream << "# script security: allow program exec" << "\n";
                        openvpn_stream << "script-security 2" << "\n";
                        openvpn_stream << "\n";
                    }

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

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

                    openvpn_stream << "" << "\n";
                    if (GlobalConfig->currentProfile->getAuthType() ==  VpnAccountData::cert) {
                        openvpn_stream << "" << "\n";
                        openvpn_stream << "# ca" << "\n";
                        openvpn_stream << "ca " << GlobalConfig->currentProfile->getCaCertificate() << "\n\n";
                        if (GlobalConfig->currentProfile->getUseSmartcard()) {
                            /* use cert on smartcard */
                            openvpn_stream << "# use smartcard" << "\n";
                            openvpn_stream << "pkcs11-providers \"" << GlobalConfig->currentProfile->getPkcs11Providers() << "\"\n";
                            openvpn_stream << "pkcs11-id \"" << GlobalConfig->currentProfile->getPkcs11Id() << "\"\n";
                            if ((OpenvpnMajor == 2 && OpenvpnMinor == 1 && OpenvpnExtraVer < 10 && OpenvpnExtra == "rc") || (OpenvpnMajor < 2)) {
                                if (GlobalConfig->KvpncDebugLevel > 3)
                                    GlobalConfig->appendLogEntry(i18n("OpenVPN =< 2.1-rc9 detected, adding additional pkcs11 parameters."), KVpncEnum::info);

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

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

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

                                    }
                                }
                            } // if real cert
                        }

                        openvpn_stream << "# client side" << "\n";
                        openvpn_stream << "tls-client" << "\n";
                        openvpn_stream << "pull" << "\n\n";

                        openvpn_stream << "# diffie hellman parameters" << "\n";
                        openvpn_stream << "dh dh1024.pem" << "\n\n";

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

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


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

                    } else {
                        openvpn_stream << "" << "\n";
                        openvpn_stream << "# use tcp" << "\n";
                        openvpn_stream << "proto tcp-client" << "\n\n";
                    }

                    openvpn_stream << "" << "\n";
                    openvpn_stream << "# remote side" << "\n";
                    openvpn_stream << "remote " << GlobalConfig->currentProfile->getGateway();
                    //      openvpn_stream << "remote " << GlobalConfig->TmpGatewayIP;;
                    if (GlobalConfig->currentProfile->getUseRemotePort())
                        openvpn_stream << " " << GlobalConfig->currentProfile->getRemotePort();
                    openvpn_stream << "\n\n";

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


//       QString RemoteNetAddr = GlobalConfig->currentProfile->getRemoteNetAddr();
//       int RemoteNetMaskNum = GlobalConfig->currentProfile->getRemoteNetMask().toInt();
//       QString RemoteNetMask = "255.255.255.0";
//       if ( RemoteNetMaskNum == 24 )
//        RemoteNetMask = "255.255.255.0";
//       else if ( RemoteNetMaskNum == 25 )
//        RemoteNetMask = "255.255.255.128";
//       else if ( RemoteNetMaskNum == 26 )
//        RemoteNetMask = "255.255.255.192";
//       else if ( RemoteNetMaskNum == 27 )
//        RemoteNetMask = "255.255.255.224";
//       else if ( RemoteNetMaskNum == 28 )
//        RemoteNetMask = "255.255.255.240";
//       else if ( RemoteNetMaskNum == 29 )
//        RemoteNetMask = "255.255.255.248";
//       else if ( RemoteNetMaskNum == 30 )
//        RemoteNetMask = "255.255.255.252";
//       else if ( RemoteNetMaskNum == 31 )
//        RemoteNetMask = "255.255.255.254";
//       else if ( RemoteNetMaskNum == 32 )
//        RemoteNetMask = "255.255.255.255";
//
//       openvpn_stream << "" << "\n";
//       openvpn_stream << "# route to remote network" << "\n";
//       openvpn_stream << "route " << RemoteNetAddr << " " << RemoteNetMask << "\n";
                    }
                    //openvpn_stream << "" << "\n";
                    //openvpn_stream << "# permissions" << "\n";
                    //      openvpn_stream << "user nobody" << "\n";
                    //      openvpn_stream << "group nogroup" << "\n";

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

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

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

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

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


                    if (GlobalConfig->currentProfile->getUseFragment()) {
                        openvpn_stream << "\n";
                        openvpn_stream << "# userdefined packet size for fragmentation" << "\n";
                        openvpn_stream << "fragment " << GlobalConfig->currentProfile->getFragment() << "\n\n";
                    }

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

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

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

                    openvpn_stream << "# disable ping restart\n";
                    openvpn_stream << "ping-restart 0\n";
                    openvpn_stream << "\n";



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

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

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

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

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

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

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

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


                    }

                    if (GlobalConfig->currentProfile->getUseHttpProxy()) {
                        openvpn_stream << "# Use a HTTP proxy\n";
                        QString HttpProxyAuthType = "";

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

                        openvpn_stream << "http-proxy " << GlobalConfig->currentProfile->getHttpProxy() << " " << GlobalConfig->currentProfile->getHttpProxyPort() << " " << "auto" << " " << HttpProxyAuthType << "\n";

                        openvpn_stream << "http-proxy-timeout " << GlobalConfig->currentProfile->getHttpProxyTimeout() << "\n\n";
                    }

                    openvpn_stream << "up " << tmpPath << "openvpn." << GlobalConfig->currentProfile->getName() << ".up" << "\n";
                    openvpn_stream << "down " << tmpPath + "openvpn." << GlobalConfig->currentProfile->getName() << ".down" << "\n";
//      openvpn_stream << "up-restart" << "\n";
                    openvpn_stream << "\n";

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

                        //       GlobalConfig->appendLogEntry( "use auth with pass: ", KVpncEnum::debug );
                        //       openvpn_stream << "management-hold\n";
//       openvpn_stream << "management-query-passwords\n";

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

                        // FIXME: can user auth only used in cert mode?
                        if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()) {
                            openvpn_stream << "# we want to authenticate with username and password\n";
                            openvpn_stream << "auth-user-pass" << "\n";
                            //        openvpn_stream << "auth-user-pass " << OpenvpnSecrectPath << "\n\n";

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

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

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


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

                // write openvpn.<profile>.up
                QFile upfile(tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".up");
                QTextStream upstream(&upfile);
                if (upfile.open(QIODevice::WriteOnly)) {
                    upstream <<  "#!" << GlobalConfig->InterpreterShell << "\n";
                    upstream << "# generated by kvpnc. Do not edit it." << "\n";
                    upstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
                    /* uses parts of http://www.smop.co.uk/node/69 */
                    //      upstream << "if [ -f /sbin/resolvconf ]; then\n";
                    //          if [ -x /sbin/resolvconf ] ; then
                    //         (
                    //         if [ "$CISCO_DEF_DOMAIN" ] ; then
                    //             echo domain "$CISCO_DEF_DOMAIN"
                    //             echo search "$CISCO_DEF_DOMAIN"
                    //         fi
                    //         for ip in "$INTERNAL_IP4_DNS" ; do
                    //             echo nameserver $ip
                    //         done
                    //         ) | /sbin/resolvconf -a $TUNDEV
                    //         return
                    //     fi
                    //      upstream << "else\n";
                    upstream << "cat /etc/resolv.conf > " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << "\n";
                    /* update dns? */
                    if (GlobalConfig->currentProfile->getUseDnsUpdate()) {
                        upstream << "echo \"# generated by kvpnc. Do not edit it.\" > /etc/resolv.conf" << "\n";
                        upstream << "echo \"# profile: " + GlobalConfig->currentProfile->getName() << "\" >> /etc/resolv.conf" << "\n";

                        upstream << "# init variables" << "\n";
                        upstream << "" << "\n";
                        upstream << "i=1" << "\n";
                        upstream << "j=1" << "\n";
                        upstream << "unset fopt" << "\n";
                        upstream << "unset dns" << "\n";
                        upstream << "unset opt" << "\n";
                        upstream << "" << "\n";
                        upstream << "dns_found=0" << "\n";
                        upstream << "domain_found=0" << "\n";
                        upstream << "" << "\n";
                        upstream << "# Convert ENVs to an array" << "\n";
                        upstream << "" << "\n";
                        //      upstream << "export > /tmp/a.txt" << "\n";
                        //      upstream << "echo \"-------\" >> /tmp/a.txt" << "\n";
                        //      upstream << "set >> /tmp/a.txt" << "\n";
                        //      upstream << "echo $foreign_option_0 > /tmp/a.txt" << "\n";
                        //      upstream << "echo $foreign_option_1 >> /tmp/a.txt" << "\n";
                        //      upstream << "echo $foreign_option_2 >> /tmp/a.txt" << "\n";
                        //      upstream << "echo $foreign_option_3 >> /tmp/a.txt" << "\n";

                        upstream << "while fopt=\"foreign_option_$i\"; [ -n \"${!fopt}\" ]; do" << "\n";
                        upstream << "{" << "\n";
                        upstream << " opt[i-1]=${!fopt}" << "\n";
                        upstream << " case ${opt[i-1]} in" << "\n";
                        upstream << "  *DOMAIN* ) domain=`echo ${opt[i-1]} | \\" << "\n";
                        upstream << "    sed -e 's/dhcp-option DOMAIN //g'` ;;" << "\n";
                        upstream << "  *DNS*    ) dns[j-1]=`echo ${opt[i-1]} | \\" << "\n";
                        upstream << "    sed -e 's/dhcp-option DNS //g'`" << "\n";
                        upstream << "          let j++ ;;" << "\n";
                        upstream << " esac" << "\n";
                        upstream << " let i++" << "\n";
                        upstream << "}" << "\n";
                        upstream << "done" << "\n";
                        upstream << "" << "\n";
                        upstream << "# Now, do the work" << "\n";
                        upstream << "" << "\n";
                        upstream << "dns_found=0" << "\n";
                        upstream << "if [ -n \"${dns[*]}\" ]; then" << "\n";
                        upstream << "if [ -x /sbin/resolvconf ] ; then\n";
                        upstream << "  echo > " + tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
                        upstream << "		echo \"# nameservers\" >> "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
                        upstream << "  nameserver_found=0" << "\n";
                        upstream << "  for i in \"${dns[@]}\"; do" << "\n";
                        upstream << "   echo \"nameserver ${i}\" >> " + tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
                        upstream << "   nameserver_found=1" << "\n";
                        upstream << "   dns_found=1" << "\n";
                        upstream << "  done" << "\n";
                        upstream << "  if [ \"$nameserver_found\" = \"0\" ]; then" << "\n";
                        upstream << "   echo \"# old nameserver\" >> " + tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
                        upstream << "   cat   " + tmpPath + "/resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() + " | grep nameserver >> " + tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
                        upstream << "  fi" << "\n";
                        upstream << "else" << "\n";
                        upstream << "  nameserver_found=0" << "\n";
                        upstream << "  for i in \"${dns[@]}\"; do" << "\n";
                        upstream << "   nameserver_found=1" << "\n";
                        upstream << "   sed -i -e \"1,1 i nameserver ${i}\" /etc/resolv.conf || die" << "\n";
                        upstream << "  done" << "\n";
                        upstream << "  if [ \"$nameserver_found\" = \"0\" ]; then" << "\n";
                        upstream << "    echo \"# old nameserver\" >> "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
                        upstream << "    cat   "+tmpPath + "/resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() +" | grep nameserver >> "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
                        upstream << "  fi" << "\n";
                        upstream << "fi" << "\n";
                        upstream << "fi" << "\n";
                        upstream << "" << "\n";
                        upstream << "echo \"# domains\" >> "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
                        upstream << "if [ -n \"${domain}\" ]; then" << "\n";
                        upstream << "if [ -x /sbin/resolvconf ] ; then\n";
                        upstream << "  echo domain \"${domain}\n\" >> " + tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
                        upstream << "else" << "\n";
                        upstream << " sed -i -e \"$j,1 i search ${domain}\" /etc/resolv.conf || die" << "\n";
                        upstream << "fi" << "\n";
                        upstream << "domain_found=1" << "\n";
                        upstream << "fi" << "\n";
                        upstream << "if [ \"$dns_found\" = \"0\" ]; then" << "\n";
                        upstream << "if [ -x /sbin/resolvconf ] ; then\n";
                        upstream << "  echo \"# old nameserver\" >> "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
                        upstream << "  cat "+tmpPath + "/resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() +" |  grep  nameserver >> "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
                        upstream << "else" << "\n";
                        upstream << "  echo \"# old nameserver\" >> "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
                        upstream << "  cat "+tmpPath + "/resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() +" |  grep  nameserver >> /etc/resolv.conf" <<"\n";
                        upstream << "fi" << "\n";
                        upstream << "fi" << "\n";
                        upstream << "if [ \"$domain_found\" = \"0\" ]; then" << "\n";
                        upstream << "if [ -x /sbin/resolvconf ] ; then\n";
                        upstream << "  echo > /dev/null\n";
                        upstream << "  echo \"# old domain\" >> "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
                        upstream << "  cat "+tmpPath + "/resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() +" |  grep  domain >> "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
                        upstream << "else" << "\n";
                        upstream << "	echo \"# old domain\" >> "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
                        upstream << "	cat "+tmpPath + "/resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() +" |  grep  domain >> /etc/resolv.conf" <<"\n";
                        upstream << "fi" << "\n";
                        upstream << "fi" << "\n";

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

                        /* crissi: -u seems not nessary */
                        //upstream << "  cat   " + tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << " | /sbin/resolvconf -u\n";


                        //      upstream << "  cat "+tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << " > /tmp/resolv "<< "\n";

                        //      upstream << "echo \"dev: ${dev}\" > /tmp/resolvup.txt" << "\n";
                        //      upstream << "cat   "+tmpPath + "/openvpn.resolvconf.tmp >> "+tmpPath + "+resolvconf." + GlobalConfig->currentProfile->getName()+ "\n";
                        if (!GlobalConfig->holdGeneratedScripts)
                            upstream << "  rm -f   " + tmpPath + "/openvpn.resolvconf.tmp." + GlobalConfig->currentProfile->getName() << "\n";
                        upstream << "fi" << "\n";

                        //      upstream << "if [ -f " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " ]; then" << "\n";
                        //      upstream << " cat  " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " | grep nameserver >> /etc/resolv.conf" << "\n";
                        //      upstream << " cat  " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " | grep domain >> /etc/resolv.conf" << "\n";
                        //      upstream << "fi" << "\n";
                        upstream << "" << "\n";

//                         upstream << "chmod u-w  /etc/resolv.conf\n";
                    } else {
                        /* dont update dns */
                        setenv("DNS_UPDATE", "NO", 1);
                    }
                    upstream << "exit 0\n";
                    upfile.close();
                }


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

                // write openvpn.<profile>.down
                QFile downfile(tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".down");
                QTextStream downstream(&downfile);
                if (downfile.open(QIODevice::WriteOnly)) {
                    downstream <<  "#!" << GlobalConfig->InterpreterShell << "\n";
                    downstream << "# generated by kvpnc. Do not edit it." << "\n";
                    downstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";

                    /* update dns? */
                    if (GlobalConfig->currentProfile->getUseDnsUpdate()) {
//                         downstream << "chmod u+w  /etc/resolv.conf\n";
                        downstream << "if [ -x /sbin/resolvconf ] ; then\n";
                        downstream << " dev=$1\n";
                        downstream << " if [ -z $dev ] ; then\n";
                        if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tun")
                            downstream << "  dev=\"tun0\"\n";
                        else
                            downstream << "  dev=\"tap0\"\n";
                        downstream << " fi\n";
                        downstream << " /sbin/resolvconf -d $dev\n";
                        downstream << "else" << "\n";
                        downstream << " cat " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " > /etc/resolv.conf\n";
                        downstream << "fi" << "\n";
                    } else {
                        /* dont update dns */
                    }
                    QString OldDefaultroute = tmpPath + "default-route." + GlobalConfig->currentProfile->getName(); // default-route.<id>
                    if (! pppdHasReplacedefaultrouteSupport && GlobalConfig->currentProfile->getReplaceDefaultRoute()) {
                        downstream << GlobalConfig->pathToIp << " route add  $(cat " << OldDefaultroute << ")" << "\n";
                    }
                    if (! pppdHasReplacedefaultrouteSupport && GlobalConfig->currentProfile->getReplaceDefaultRoute()) {
                        downstream << GlobalConfig->pathToIp << " route add  $(cat " << OldDefaultroute << ")" << "\n";
                    }


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

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

                OldDefaultroute = tmpPath + "default-route." + GlobalConfig->currentProfile->getName(); // default-route.<id>

                QFile DefaultRouteBackupFile(OldDefaultroute + ".sh");
                QTextStream DefaultRouteBackupFileStream(&DefaultRouteBackupFile);
                if (DefaultRouteBackupFile.open(QIODevice::WriteOnly)) {
                    DefaultRouteBackupFileStream << "# generated by kvpnc. Do not edit it." << "\n";
                    DefaultRouteBackupFileStream << "\n";
                    DefaultRouteBackupFileStream << GlobalConfig->pathToIp + " route show | grep default > " + OldDefaultroute + "\n";
                    DefaultRouteBackupFile.close();
                    QProcess backupDefaultRouteProcess(this);
                    QString proc = GlobalConfig->InterpreterShell;
                    QStringList args;
                    args.append(OldDefaultroute + ".sh");
                    backupDefaultRouteProcess.setEnvironment(*env);
                    backupDefaultRouteProcess.start(proc, args);
                    if (!backupDefaultRouteProcess.waitForStarted()) {
                        //     if ( GlobalConfig->KvpncDebugLevel > 0 )
                        GlobalConfig->appendLogEntry(i18n("Connect canceled because default route backup process could not be started."), KVpncEnum::error);
                        return ;
                    } else {
                        if (GlobalConfig->KvpncDebugLevel > 2)
                            GlobalConfig->appendLogEntry(i18n("Default route backup process started."), KVpncEnum::debug);

                        waitForFinished(&backupDefaultRouteProcess,100);

                    }
                } else {
                    //    if ( GlobalConfig->KvpncDebugLevel > 0 )
                    GlobalConfig->appendLogEntry(i18n("Connect canceled because a backup of the default route could not be created."), KVpncEnum::error);
                    return ;
                }

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

                OpenvpnProcess = new QProcess(this);
                OpenvpnProcess->setProcessChannelMode(QProcess::MergedChannels);
                QString proc = GlobalConfig->pathToOpenvpn;
                QStringList args;

                args.append("--writepid");
                args.append(tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".pid");
                args.append("--config");
                args.append(tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".conf");    // default

                connect(OpenvpnProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutput_openvpn()));
                //connect( OpenvpnProcess, SIGNAL( readyReadStandardError() ), this, SLOT( readOutput_openvpn() ) );
                connect(OpenvpnProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(openvpn_exited(int, QProcess::ExitStatus)));



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

                setenv("DNS_UPDATE", (GlobalConfig->currentProfile->getUseDnsUpdate() ? "Yes" : "NO"), 1);

                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Setting DNS_UPDATE \"%1\"." , QString(qgetenv("DNS_UPDATE"))), KVpncEnum::debug);

                OpenvpnProcess->setEnvironment(*env);
                OpenvpnProcess->start(proc, args);
                if (!OpenvpnProcess->waitForStarted()) {
                    disconnect(OpenvpnProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutput_openvpn()));
                    //disconnect( OpenvpnProcess, SIGNAL( readyReadStandardError() ), this, SLOT( readOutput_openvpn() ) );
                    disconnect(OpenvpnProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(openvpn_exited(int, QProcess::ExitStatus)));
                    KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , QString("openvpn")));
                    GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("openvpn")) , KVpncEnum::error);
                    disconnectClicked();
                } else {
                    ConnectingProcess = VpnAccountData::openvpn;
                    GlobalConfig->status = KVpncEnum::connecting;
                    mw->buttonDisconnect->setEnabled(true);
                    this->DisconnectAction->setEnabled(true);
                    mw->buttonConnect->setEnabled(false);
                    this->ConnectAction->setEnabled(false);


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

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

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


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

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

                        //     sleep(5);

                        if (! GlobalConfig->KvpncDebugLevel > 0)
                            GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString("openvpn")), KVpncEnum::debug);
                    }
                    else {
                        GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed.", QString("openvpn managementhandler") ), KVpncEnum::error );
                        disconnectClicked();
                    }


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

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

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

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

        bool tunsupportfound = false;
        QString procmisc = "";
        QFile f("/proc/misc");
        if (f.open(QIODevice::ReadOnly)) {
            QStringList contentlist = QString(f.readAll()).split("\n");
            for (int i = 0; i < contentlist.size(); ++i) {
                QString line = contentlist.at(i);
                if (line.contains("tun", Qt::CaseInsensitive)) {
                    tunsupportfound = true;
                    break;
                }
            }
        }
        f.close();
        if (tunsupportfound) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Support for TUN/TAP found (compiled into kernel or kernel module already loaded)."), KVpncEnum::debug);

            QFile tundevfile("/dev/net/tun");
            if (!tundevfile.exists()) {
                if (!Utils(GlobalConfig, parent).createTunDev()) {
                    KMessageBox::error(this, i18n("Failed to create \"%1\"." , QString("/dev/net/tun")));
                    GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, creating it has failed: stop."), KVpncEnum::error);
                    disconnectClicked();
                    setGuiStatus(KVpncEnum::disconnected);
                    GlobalConfig->status = KVpncEnum::disconnected;
                    return ;
                } else {
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, creating has been successful."), KVpncEnum::debug);
                }
            } else {
                // load the module 'tun'
                if (!Utils(GlobalConfig, parent).loadKernelModule("tun", parent)) {
                    KMessageBox::information(this, i18n("Loading of module \"%1\" failed." , QString("tun")));
                    GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, loading module \"%1\" has failed: stop." , QString("tun")), KVpncEnum::error);
                    disconnectClicked();
                    setGuiStatus(KVpncEnum::disconnected);
                    GlobalConfig->status = KVpncEnum::disconnected;
                    return ;
                } else {
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("Loading of module \"%1\" was successful." , QString("tun")), KVpncEnum::debug);
                }
            }
        }

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

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

        if (!GlobalConfig->haveUserData) {

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

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

        if (GlobalConfig->currentProfile->getAskUserPasswordOnEachConnect()) {
            if (GlobalConfig->KvpncDebugLevel > 4)
                GlobalConfig->appendLogEntry(i18n("User password on each connect forced."), KVpncEnum::debug);

            askUsernamePass = true;
            requestUsername = true;
        }

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


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

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

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


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

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

                bool needSave = false;

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


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

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

                if (needSave)
                    GlobalConfig->saveOptions(true, GlobalConfig->currentProfile->getName());

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

        } else {
            if (!GlobalConfig->currentProfile->getSaveUserPassword() && ! GlobalConfig->currentProfile->getUserPassword().isEmpty()) {
                GlobalConfig->TmpPassword =  GlobalConfig->currentProfile->getUserPassword() ;
            }


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

        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("Some passwords which were needed were obtained from a password dialog."), KVpncEnum::debug);

        AuthRetry = false;
        GlobalConfig->haveUserData = true;

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

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

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

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

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

            }
            vtun_file.close();

            VtundProcess = new QProcess(this);
            //VtundProcess->setProcessChannelMode(QProcess::MergedChannels );
            QString proc = GlobalConfig->pathToVtund;
            QStringList args;
            args.append("-n");
            args.append("-f");
            args.append(tmpPath + "vtun." + GlobalConfig->currentProfile->getName() + ".conf");    // default
            args.append(GlobalConfig->currentProfile->getVtunProfile());
            args.append(GlobalConfig->currentProfile->getGateway());


            connect(VtundProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_vtun()));
            connect(VtundProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_vtun()));
            connect(VtundProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(vtun_exited(int, QProcess::ExitStatus)));


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

            VtundProcess->setEnvironment(*env);
            VtundProcess->start(proc, args);
            if (!VtundProcess->waitForStarted()) {
                VtundProcess = 0L;
                KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , QString("vtund")));
                GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("vtund")) , KVpncEnum::error);
                disconnectClicked();
            } else {
                ConnectingProcess = VpnAccountData::vtun;
                GlobalConfig->status = KVpncEnum::connecting;
                mw->buttonDisconnect->setEnabled(true);
                this->DisconnectAction->setEnabled(true);
                mw->buttonConnect->setEnabled(false);
                this->ConnectAction->setEnabled(false);

                GlobalConfig->currentConnectRetry++;

            }

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

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

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

        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("ssh: %1" , QString(GlobalConfig->pathToSsh)) , KVpncEnum::debug);

        bool tunsupportfound = false;
        QString procmisc = "";
        QFile f("/proc/misc");
        if (f.open(QIODevice::ReadOnly)) {
            QStringList contentlist = QString(f.readAll()).split("\n");
            for (int i = 0; i < contentlist.size(); ++i) {
                QString line = contentlist.at(i);
                if (line.contains("tun", Qt::CaseInsensitive)) {
                    tunsupportfound = true;
                    break;
                }
            }
        }
        f.close();
        if (tunsupportfound) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Support for TUN/TAP found (compiled into kernel or kernel module already loaded)."), KVpncEnum::debug);

            QFile tundevfile("/dev/net/tun");
            if (!tundevfile.exists()) {
                if (!Utils(GlobalConfig, parent).createTunDev()) {
                    KMessageBox::error(this, i18n("Failed to create \"%1\".", QString("/dev/net/tun")));
                    GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, creating it has failed: stop."), KVpncEnum::error);
                    disconnectClicked();
                    setGuiStatus(KVpncEnum::disconnected);
                    GlobalConfig->status = KVpncEnum::disconnected;
                    return ;
                } else {
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, creating has been successful."), KVpncEnum::debug);
                }
            } else {
                // load the module 'tun'
                if (!Utils(GlobalConfig, parent).loadKernelModule("tun", parent)) {
                    KMessageBox::information(this, i18n("Loading of module \"%1\" failed." , QString("tun")));
                    GlobalConfig->appendLogEntry(i18n("Tunnel device is missing, loading module \"%1\" has failed: stop." , QString("tun")), KVpncEnum::error);
                    disconnectClicked();
                    setGuiStatus(KVpncEnum::disconnected);
                    GlobalConfig->status = KVpncEnum::disconnected;
                    return ;
                } else {
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("Loading of module \"%1\" was successful.", QString("tun")), KVpncEnum::debug);
                }
            }
        }

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

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

        if (!GlobalConfig->haveUserData) {
            //   if ( GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() )
            {
                if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()) {
                    if (GlobalConfig->currentProfile->getUserPassword().isEmpty())
                        askUsernamePass = true;
                    else
                        GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserPassword();
                }
                if (GlobalConfig->currentProfile->getUserName().isEmpty())
                    requestUsername = true;
                else
                    GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();

                if (AuthRetry) {
                    askUsernamePass = true;
                    requestUsername = true;
                }
            }
        } else {
            if (GlobalConfig->KvpncDebugLevel > 4)
                GlobalConfig->appendLogEntry(i18n("User data already collected."), KVpncEnum::debug);
        }

        if (GlobalConfig->currentProfile->getAskUserPasswordOnEachConnect()) {
            if (GlobalConfig->KvpncDebugLevel > 4)
                GlobalConfig->appendLogEntry(i18n("User password on each connect forced."), KVpncEnum::debug);

            askUsernamePass = true;
            requestUsername = true;
        }

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

            if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()) {
                if (GlobalConfig->currentProfile->getSaveUserPassword())
                    dlg.PasswordEdit->setText(GlobalConfig->currentProfile->getUserPassword());
            } else {
                dlg.PasswordEdit->hide();
                dlg.LabelPassword->hide();
                dlg.SavePasswordCheckBox->hide();
            }
            dlg.UsernameEdit->setText(GlobalConfig->currentProfile->getUserName());

            if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()) {
                if (!dlg.UsernameEdit->text().isEmpty())                  //go straight to pw if username present
                    dlg.PasswordEdit->setFocus();
            }
            bool needSave = false;
            if (dlg.exec()) {
                GlobalConfig->TmpUsername = dlg.UsernameEdit->text();
                GlobalConfig->TmpPassword = dlg.PasswordEdit->text();

                if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()) {
                    if (GlobalConfig->TmpPassword.isEmpty()) {
                        GlobalConfig->appendLogEntry(i18n("Password is empty"), KVpncEnum::error);
                        ok = false;
                    }
                }
                if (requestUsername && GlobalConfig->TmpUsername.isEmpty()) {
                    GlobalConfig->appendLogEntry(i18n("Username is empty."), KVpncEnum::error);
                    ok = false;
                }

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


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

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

                if (needSave)
                    GlobalConfig->saveOptions(true, GlobalConfig->currentProfile->getName());

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

        } else {
            if (!GlobalConfig->currentProfile->getSaveUserPassword() && ! GlobalConfig->currentProfile->getUserPassword().isEmpty()) {
                GlobalConfig->TmpPassword =  GlobalConfig->currentProfile->getUserPassword() ;
            }


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

        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("Some passwords which were needed were obtained from a password dialog."), KVpncEnum::debug);

        AuthRetry = false;
        GlobalConfig->haveUserData = true;

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

            SshProcess = new KPtyProcess;
            SshPty = SshProcess->pty();
            SshProcess->setPtyChannels(KPtyProcess::AllChannels);
            SshProcess->setOutputChannelMode(KProcess::SeparateChannels);
            //SshProcess->setUseUtmp(true);

            QString proc = GlobalConfig->pathToSsh ;
            QStringList args;


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

            // FIXME make it dynamiclly
            SshDevice = "";
            if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tun")
                SshDevice = "tun0";
            else
                SshDevice = "tap0";

            // FIXME make it dynamiclly
            if (GlobalConfig->currentProfile->getUseSshConfigRemoteScript() && !GlobalConfig->currentProfile->getSshConfigRemoteScript().isEmpty()) {
                args.append("-w0");
            } else {
                args.append("-w0:0");
            }

            if (GlobalConfig->SshDebugLevel > 0) {
                QString SshDebug = "-";
                for (int i = 0; i < GlobalConfig->SshDebugLevel; i++)
                    SshDebug += "v";
//     args.append(SshDebug);
            }

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

                if (GlobalConfig->KvpncDebugLevel > 2)
                    GlobalConfig->appendLogEntry(i18n("Using keyfile: %1" , QString(GlobalConfig->currentProfile->getPreSharedKey())), KVpncEnum::debug);
                args.append(" -i");
                args.append(GlobalConfig->currentProfile->getPreSharedKey());
            }

            args.append("-t") ;
            args.append("-t") ;

            args.append("-n");

            // login name
            args.append("-l") ;
            args.append(GlobalConfig->TmpUsername);



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


            if (GlobalConfig->currentProfile->getUseRemotePort()) {
                args.append("-p");
                args.append(QString().setNum(GlobalConfig->currentProfile->getRemotePort()));
            }

            args.append(GlobalConfig->TmpGatewayIP);


            // FIXME add detection on server and make it dynamiclly
            if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tun") {
                if (!GlobalConfig->currentProfile->getUseSshConfigRemoteScript()) {
                    args.append(GlobalConfig->pathToIfconfig);
                    args.append(" " + SshDevice + " " + GlobalConfig->currentProfile->getRemoteVirtualIP() + " pointopoint " + GlobalConfig->currentProfile->getLocalVirtualIP() + " up ; /bin/echo ssh_is_up");
                } else {
                    if (!GlobalConfig->currentProfile->getSshConfigRemoteScript().isEmpty()) {
                        args.append(GlobalConfig->currentProfile->getSshConfigRemoteScript() + " tun " + GlobalConfig->currentProfile->getRemoteVirtualIP() + " " + GlobalConfig->currentProfile->getLocalVirtualIP() + " up ; /bin/echo ssh_is_up");

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

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

            if (GlobalConfig->KvpncDebugLevel > 3) {
                GlobalConfig->appendLogEntry(i18n("%1 arguments: %2", QString("ssh"), args.join(" ")), KVpncEnum::debug);
            }


            connect(SshProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ssh()));
            connect(SshProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ssh()));
            connect(SshPty, SIGNAL(readyRead()), this, SLOT(readFromPty_ssh()));
            //     connect( SshProcess, SIGNAL( finished(int, QProcess::ExitStatus) ), this, SLOT( sshExited(int, QProcess::ExitStatus) ) );

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

            QStringList environment;
            environment.append("LC_ALL=C");
            environment.append("LANG=C");
            environment.append("PATH=/bin:/usr/bin:/usr/sbin:/sbin");
//      environment.append( "SSH_ASKPASS",AskPassScript );

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

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

            SshProcess->setEnvironment(environment);
            SshProcess->setProgram(proc, args);
            SshProcess->start();
            if (!SshProcess->waitForStarted()) {
                KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , QString("ssh")));
                GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("ssh")) , KVpncEnum::error);
                disconnectClicked();
            } else {
                ConnectingProcess = VpnAccountData::ssh;
                GlobalConfig->status = KVpncEnum::connecting;
                mw->buttonDisconnect->setEnabled(true);
                this->DisconnectAction->setEnabled(true);
                mw->buttonConnect->setEnabled(false);
                this->ConnectAction->setEnabled(false);

                GlobalConfig->currentConnectRetry++;
            }

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

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

        if ( GlobalConfig->KvpncDebugLevel > 1 )
            GlobalConfig->appendLogEntry ( i18n ( "l2tpd_plain" ), KVpncEnum::debug );

        //setGuiStatus(connecting);
        if ( Utils ( GlobalConfig ).getToolInfo ( "l2tpd" )->found == false && Utils ( GlobalConfig ).getToolInfo ( "xl2tpd" )->found == false ) {
            KMessageBox::error ( this, i18n ( "Unable to find \"%1\" or \"%2\"!" ).arg ( "l2tpd" ).arg ( "xl2tpd" ) );
            GlobalConfig->appendLogEntry ( i18n ( "Unable to find \"%1\" or \"%2\"!" ).arg ( "l2tpd" ).arg ( "xl2tpd" ), KVpncEnum::error );
            ok = false;
            setGuiStatus ( KVpncEnum::disconnected );
            return ;
        }

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



        if ( ok==false )
            return;

        bool askUsernamePass = false;
        bool askPsk = false;

        if ( GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() ) {
            if ( !GlobalConfig->haveUserData ) {
                GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();
                GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserPassword();

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

                GlobalConfig->WaitingForXauth=false;
                GlobalConfig->haveUserData=true;
            } else {
                if ( GlobalConfig->KvpncDebugLevel > 4 )
                    GlobalConfig->appendLogEntry ( i18n ( "User data already collected." ), KVpncEnum::debug );
            }
        }

        if ( AuthRetry )
            askUsernamePass = true;

        if ( GlobalConfig->currentProfile->getAskUserPasswordOnEachConnect() ) {
            if ( GlobalConfig->KvpncDebugLevel > 4 )
                GlobalConfig->appendLogEntry ( i18n ( "User password on each connect forced." ), KVpncEnum::debug );

            askUsernamePass = true;
        }

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

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

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

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

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

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

                if ( askPsk || AuthRetry ) {

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

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


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

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

                if ( ok ) {
                    if ( GlobalConfig->KvpncDebugLevel > 0 )
                        GlobalConfig->appendLogEntry ( i18n ( "Some account data which is needed got from password enter dialog." ), KVpncEnum::debug );
                    // 					saveSessionClicked();
                }
            } else {
                ok = false;
                AuthRetry = false;
                if ( GlobalConfig->KvpncDebugLevel > 0 )
                    GlobalConfig->appendLogEntry ( i18n ( "Connect canceled because account data dialog aborted." ), KVpncEnum::debug );
            }
        }

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

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

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



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

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



            setenv ( "DNS_UPDATE", ( GlobalConfig->currentProfile->getUseDnsUpdate() ? "Yes" : "NO" ), 1 );

            if ( GlobalConfig->KvpncDebugLevel > 0 )
                GlobalConfig->appendLogEntry ( i18n ( "Setting DNS_UPDATE \"%1\"." ).arg ( getenv ( "DNS_UPDATE" ) ), KVpncEnum::debug );

            prepareL2tpd(true);

            OpenL2tpProcess=0L;
            L2tpdProcess=0L;

            ConnectingProcess = VpnAccountData::l2tpd_plain;
            GlobalConfig->status = KVpncEnum::connecting;
            mw->buttonDisconnect->setEnabled ( true );
            this->DisconnectAction->setEnabled ( true );
            mw->buttonConnect->setEnabled ( false );
            this->ConnectAction->setEnabled ( false );

            start_l2tpd();
        } else {
            disconnectClicked();
        }
    } // l2tpd_plain




}

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

    DisconnectAction->setEnabled(false);

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

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

        if (ConnectionStatusCheckProcess != 0) {
            if (ConnectionStatusCheckProcess->state() == QProcess::Running) {
                disconnect(ConnectionStatusCheckProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_connectionStatusCheck()));
                disconnect(ConnectionStatusCheckProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_connectionStatusCheck()));

                ConnectionStatusCheckProcess->kill();

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

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

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

                tmpPath = KStandardDirs::locateLocal("data", "kvpnc/");
                //Vpnc_pid_file = tmpPath + "vpnc-pid." + GlobalConfig->currentProfile->getID() + ".pid"; // vpnc-pid.<id>.pid
                VpncDisconnectScript = tmpPath + "vpnc-disconnect." + GlobalConfig->currentProfile->getID() + ".sh";
                // write vpnc connect script
                QFile pidFile(GlobalConfig->Vpnc_pid_file);
                QString Vpnc_pid = "";
                if (pidFile.open(QIODevice::ReadOnly)) {
                    Vpnc_pid = QString(pidFile.readAll()).trimmed();
                }

                if ( VpncProcess != 0 ) {
                    if ( VpncProcess->state() == QProcess::Running ) {
                        disconnect(VpncProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutputFrom_vpnc()));
                        disconnect(VpncProcess, SIGNAL(readyReadStandardError()), this, SLOT(readOutputFrom_vpnc()));
                        disconnect(&timer, SIGNAL(timeout()), this, SLOT(slotConnectTimedOut()));

                        VpncProcess->kill();
                        sleep ( 1 );
                        if ( VpncProcess->state() == QProcess::Running ) {
                            VpncProcess->kill();
                            sleep ( 1 );
                        }
                        if ( VpncProcess->state() == QProcess::Running ) {
                            VpncProcess->kill();
                            sleep ( 1 );
                        }
                        if ( VpncProcess->state() == QProcess::Running )
                            VpncProcess->kill();
                    }
                    delete VpncProcess;
                    VpncProcess = 0L;
                }

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

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

                    if ( GlobalConfig->currentProfile->getUseDnsUpdate() ) {
                        // FIXME this is a temporary fix for not calling vpnc script with disconnect at disconnect time!
                        if (VpncDevice.isEmpty())
                            VpncDevice = "tun0";
                        stream << "    if [ -f /sbin/resolvconf ] ; then\n";
                        stream << "        /sbin/resolvconf -d \"" << VpncDevice <<  "\"\n";
                        stream << "    else\n";
                        stream << "        cat " + tmpPath + "resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() + " > /etc/resolv.conf\n";
                        stream << "    fi\n";
                        // end temp fix
                    } else {
                        /* dont update dns */
                    }

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

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

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

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

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

                    file.close();

                    DisconnectProcess = new QProcess();
                    QString proc = GlobalConfig->InterpreterShell;
                    QStringList args;
                    args.append(VpncDisconnectScript);
                    DisconnectProcess->setEnvironment(*env);

                    connect(DisconnectProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_disconnect()));
                    connect(DisconnectProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_disconnect()));

                    DisconnectProcess->setEnvironment(*env);
                    DisconnectProcess->start(proc, args);
                    if (!DisconnectProcess->waitForStarted()) {
                        KMessageBox::sorry(this, i18n("Failed to start \"%1\".", QString("vpnc_disconnect")));
                    } else {
                        waitForFinished(DisconnectProcess, 100);
                    }
                    disconnect(DisconnectProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_disconnect()));
                    disconnect(DisconnectProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_disconnect()));
                    delete DisconnectProcess;
                    DisconnectProcess = 0L;


                }

                setGuiStatus(KVpncEnum::disconnected);
                durationTimer.stop();
                disconnect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));
                connectionEnded();
            }
            // vpnclient
            else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig) {
                tmpPath = KStandardDirs::locateLocal("data", "kvpnc/");
                QString CiscoVpncDisconnectScript = tmpPath + "vpnclient-disconnect." + GlobalConfig->currentProfile->getID() + ".sh";
                // write vpnc connect script

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

//      if ( GlobalConfig->currentProfile->getReplaceDefaultRoute() )
//      {
//       if ( GlobalConfig->KvpncDebugLevel > 2 )
//        GlobalConfig->appendLogEntry ( i18n ( "Restoring default route before connection..." ), KVpncEnum::debug );
//
//       QString OldDefaultroute = tmpPath + "default-route." + GlobalConfig->currentProfile->getName(); // default-route.<id>
//       stream << GlobalConfig->pathToIp + " route del default > /dev/null 2>&1\n";
//       stream << GlobalConfig->pathToIp + " route add $(cat \"" + OldDefaultroute + "\")\n";
//       //       stream << GlobalConfig->pathToIp + " route add $(cat \"/var/run/vpnc/defaultroute\")\n";
//      }
//      //     stream << GlobalConfig->pathToIp+" route del $(cat \"" + VpncGateway + "\")\n";

                    /* update dns? */
                    if (GlobalConfig->currentProfile->getUseDnsUpdate()) {
                        //stream << "chmod u+w  /etc/resolv.conf\n";
                        stream << "if [ -f /sbin/resolvconf ] ; then\n";
                        stream << " /sbin/resolvconf -d "+GlobalConfig->DnsDevice+"\n";
                        stream << "else\n";
                        stream << " cat " + tmpPath + "resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() + " > /etc/resolv.conf\n";

                        stream << "fi\n";
                    } else {
                        /* dont update dns */
                    }

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

                }
                file.close();

                DisconnectProcess = new QProcess();
                QString proc = GlobalConfig->InterpreterShell;
                QStringList args;
                args.append(CiscoVpncDisconnectScript);
                DisconnectProcess->setEnvironment(*env);
                connect(DisconnectProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_disconnect()));
                connect(DisconnectProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_disconnect()));

                DisconnectProcess->setEnvironment(*env);
                DisconnectProcess->start(proc, args);
                if (!DisconnectProcess->waitForStarted()) {
                    KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , QString("vpnc_disconnect")));
                } else {
                    waitForFinished(DisconnectProcess, 100);
                }
                disconnect(DisconnectProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_disconnect()));
                disconnect(DisconnectProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_disconnect()));

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


                if (CiscoVpncProcess != 0 && CiscoVpncProcess->state() == KProcess::Running)
                    CiscoVpncProcess->terminate();
                sleep(1);
                if (CiscoVpncProcess != 0 && CiscoVpncProcess->state() == KProcess::Running)
                    CiscoVpncProcess->kill();

                delete CiscoVpncProcess;
                CiscoVpncProcess = 0L;

                setGuiStatus(KVpncEnum::disconnected);
                disconnect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));
                connectionEnded();
            }
            // racoon
            else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon) {

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



                QFile file2(tmpPath + "setkey." + GlobalConfig->currentProfile->getName() + ".remove_setkey.sh");
                QTextStream stream2(&file2);
                if (file2.open(QIODevice::WriteOnly)) {
                    stream2 <<  "#!" << GlobalConfig->InterpreterShell << "\n";
                    stream2 << "# generated by kvpnc. Do not edit it." << "\n";
                    stream2 << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";
                    stream2 << GlobalConfig->pathToSetkey << " -PF" << "\n";
                    stream2 << GlobalConfig->pathToSetkey << " -F" << "\n";
                    file2.close();
                    if (GlobalConfig->KvpncDebugLevel > 1)
                        GlobalConfig->appendLogEntry(i18n("\"%1\" write successful." , QString("setkey (remove)")) , KVpncEnum::debug);
                } else {
                    //      KMessageBox::error( this, i18n( "\"%1\" write failed." , QString("setkey (remove)") ) );
                    GlobalConfig->appendLogEntry(i18n("\"%1\" write failed.", QString("setkey (remove)")) , KVpncEnum::error);
                }

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

                            disconnect(this, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_l2tpd()));
                            disconnect(this, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_l2tpd()));

                            L2tpdProcess->kill();
//        if (L2tpdProcess->state() == QProcess::Running )
                            //L2tpdProcess->terminate();
                            sleep(1);
                            if (L2tpdProcess != 0L  && L2tpdProcess->state() == QProcess::Running)
                                L2tpdProcess->kill();
                        }
                    }
                    if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp) {
                        if (OpenL2tpProcess != 0L && OpenL2tpProcess->state() == QProcess::Running) {

                            disconnect(OpenL2tpProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_openl2tp()));
                            disconnect(OpenL2tpProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_openl2tp()));

                            //OpenL2tpProcess->Terminate();
                            sleep(1);
                            //if (OpenL2tpProcess->state() == QProcess::Running)
                            // OpenL2tpProcess->terminate();
                            sleep(1);
                            if (OpenL2tpProcess != 0L  && OpenL2tpProcess->state() == QProcess::Running)
                                OpenL2tpProcess->kill();

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

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

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

                        }
                    }
//      }
                }
                if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon && GlobalConfig->currentProfile->getUseLeftSourceIp()) {
                    if ( GlobalConfig->KvpncDebugLevel > 3 )
                        GlobalConfig->appendLogEntry ( i18n ( "Removing virtual IP address" ), KVpncEnum::debug );
                    doAddRemoveVirtualIp("del");
                }

                stopRacoon();

                if (RacoonTailProcess != 0 && RacoonTailProcess->state() == QProcess::Running) {
                    disconnect(RacoonTailProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_tail_racoon()));
                    disconnect(RacoonTailProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_tail_racoon()));
                    //      terminateConnection( RacoonTailProcess );

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

                    RacoonTailProcess->terminate();

                    while (RacoonTailProcess != 0 && RacoonTailProcess->state() == QProcess::Running) {
                        sleep(1);
                        if (GlobalConfig->KvpncDebugLevel > 2)
                            GlobalConfig->appendLogEntry(i18n("Killing \"%1\"..."  , QString("racoon tail")) , KVpncEnum::debug);
                        RacoonTailProcess->kill();
                    }
                    if (GlobalConfig->KvpncDebugLevel > 2)
                        GlobalConfig->appendLogEntry(i18n("\"%1\" killed"  , QString("racoon tail")) , KVpncEnum::debug);

                }

                if (RacoonProcess != 0 && RacoonProcess->state() == QProcess::Running) {
                    //      disconnect ( RacoonProcess, SIGNAL ( readyReadStandardOutput() ), this, SLOT ( readFromStdout_racoon() ) );
                    //      disconnect ( RacoonProcess, SIGNAL ( readyReadStandardError() ), this, SLOT ( readFromStderr_racoon() ) );

                    //      terminateConnection( RacoonProcess );
                    if (GlobalConfig->KvpncDebugLevel > 2)
                        GlobalConfig->appendLogEntry(i18n("Trying to terminate \"%1\"..."  , QString("racoon")) , KVpncEnum::debug);
                    //RacoonProcess->terminate();
                    while (RacoonProcess != 0 && RacoonProcess->state() == QProcess::Running) {
                        sleep(1);
                        if (GlobalConfig->KvpncDebugLevel > 2)
                            GlobalConfig->appendLogEntry(i18n("Killing \"%1\"..." , QString("racoon")) , KVpncEnum::debug);

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

                }

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

                if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon && (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd ||  GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd)) {
                    // remove kvpnc entries from secrets file
                    QFile papSecretsFile("/etc/ppp/pap-secrets");
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1" , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                    if (papSecretsFile.open(QIODevice::ReadOnly)) {
                        QString line = "";
                        QString papsecret_content = "";
                        bool kvpnc_start_marker_found = false;
                        bool kvpnc_end_marker_found = false;
                        QStringList contentlist = QString(papSecretsFile.readAll()).split("\n");
                        for (int i = 0; i < contentlist.size(); ++i) {
                            QString line = contentlist.at(i);
                            if (line == "# --- generated by kvpnc. Do not edit it.") {
                                kvpnc_end_marker_found = true;
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("End marker in %1 found" , QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
                            }
                            if (line == "# +++ generated by kvpnc. Do not edit it.") {
                                kvpnc_start_marker_found = true;
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("Start marker in %1 found" , QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
                            }

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

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

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

                //RacoonProcess = new QProcess(this);
                //QString proc = GlobalConfig->InterpreterShell;
                //QStringList args;
                //args.append( GlobalConfig->pathToKillall );
                //args.append( "-3" );
                //args.append( "racoon" );
                //RacoonProcess->setEnvironment(*env);
                //     connect( RacoonProcess, SIGNAL( readyReadStandardOutput() ), this, SLOT( readFromStdout_racoon() ) );
                //     connect( RacoonProcess, SIGNAL( readyReadStandardError() ), this, SLOT( readFromStderr_racoon() ) );
                //  RacoonProcess->setEnvironment(*env);
                //  RacoonProcess->start(proc,args);
                //     if ( !RacoonProcess->waitForStarted() )
                //      KMessageBox::error( this, i18n( "Failed to start \"%1\"."  , QString("killall -3 racoon") ));
                //     else {
                //      RacoonTailProcess->terminate();
                //      if ( GlobalConfig->KvpncDebugLevel > 0 )
                //       GlobalConfig->appendLogEntry( i18n( "\"%1\" was successful."  , QString("killall -3 racoon")), KVpncEnum::debug );
                //     }

//      }
            }
            // freeswan
            else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
                // iptables need the right interface (eth0:1 => eth0)
                QString tmpInterface2 = "";
                int pointPos = tmpInterface.indexOf(QChar(':'), 0, Qt::CaseInsensitive);
                if (pointPos > 1) {
                    tmpInterface2 = tmpInterface.left(pointPos);
                } else
                    tmpInterface2 = tmpInterface;

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

                                L2tpdProcess->kill();
                                if (L2tpdProcess->state() == QProcess::Running)
                                    L2tpdProcess->terminate();
                                sleep(1);
                                if (L2tpdProcess != 0L  && L2tpdProcess->state() == QProcess::Running)
                                    L2tpdProcess->kill();
                            }
                        }
                        if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp) {
                            if (OpenL2tpProcess != 0L && OpenL2tpProcess->state() == QProcess::Running) {
                                disconnect(OpenL2tpProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_openl2tp()));
                                disconnect(OpenL2tpProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_openl2tp()));
                                OpenL2tpProcess->kill();

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

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

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

                            }
                        }

                    }
                }

                if (GlobalConfig->currentProfile->getUseLeftSourceIp()) {
                    if ( GlobalConfig->KvpncDebugLevel > 3 )
                        GlobalConfig->appendLogEntry ( i18n ( "Removing virtual IP address" ), KVpncEnum::debug );
                    doAddRemoveVirtualIp("del");
                }

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

                putenv((char*)("LC_ALL=C"));
                IpsecWhackDeleteProcess = new QProcess(this);
                QString proc = GlobalConfig->pathToIpsec;
                QStringList args;
                args.append("whack");
                args.append("--name");
                args.append(GlobalConfig->currentProfile->getName());
                args.append("--delete");

                connect(IpsecWhackDeleteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhackdelete()));
                connect(IpsecWhackDeleteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhackdelete()));

                IpsecWhackDeleteProcess->setEnvironment(*env);
                IpsecWhackDeleteProcess->start(proc, args);
                if (!IpsecWhackDeleteProcess->waitForStarted()) {
                    KMessageBox::error(this, i18n("Failed to start \"%1\"."  , QString(GlobalConfig->pathToIpsec + " whack' --name " + GlobalConfig->currentProfile->getName() + " --delete")));
                    GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString(GlobalConfig->pathToIpsec + " whack' --name " + GlobalConfig->currentProfile->getName() + " --delete")) , KVpncEnum::error);
                } else {
                    while (IpsecWhackDeleteProcess != 0 && IpsecWhackDeleteProcess->state() == QProcess::Running) {
                        if (GlobalConfig->KvpncDebugLevel > 8)
                            GlobalConfig->appendLogEntry(i18n("\"%1\" is still running, waiting for it to terminate..." , QString(GlobalConfig->pathToIpsec + " whack --name " + GlobalConfig->currentProfile->getName() + " --delete")), KVpncEnum::debug);
                        usleep(100);
                        if (GlobalConfig->appPointer->hasPendingEvents())
                            GlobalConfig->appPointer->processEvents();
                    }
                }
                disconnect(IpsecWhackDeleteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhackdelete()));
                disconnect(IpsecWhackDeleteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhackdelete()));
                delete IpsecWhackDeleteProcess;
                IpsecWhackDeleteProcess = 0L;

                // prevent old logs...
                IpsecGotError = true;


//                 IpsecStartProcess = new QProcess(this);
//                 proc = GlobalConfig->pathToIpsec;
//                 args.clear();
//
//                 if (!IpsecType.contains("Openswan", Qt::CaseInsensitive)) {
//                     args.append("setup");
//                     args.append("stop");
//                 }
//                 //     if (IpsecType.contains( "strongSwan", Qt::CaseInsensitive ) &&  ( (IpsecMajor >= 4 && IpsecMinor >= 2 && IpsecSubMinor >=2 ) || IpsecMajor > 4 ) )
//                 //     if ( ! IpsecType.contains ( "free", Qt::CaseInsensitive ) && ( (IpsecMajor = 4 && IpsecMinor >= 2 && IpsecSubMinor >= 2)  || IpsecMajor > 4))
//                 if (IpsecType.contains("strongSwan", Qt::CaseInsensitive)) {
//                     args.append("stop");
//                 }
//                 IpsecStartProcess->setEnvironment(*env);
//                 connect(IpsecStartProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStderr_ipsec()));
//                 connect(IpsecStartProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsec()));
//                 //     connect( IpsecStartProcess, SIGNAL( processExited () ), this, SLOT( removeRouteFreeswan() ) );
//
//                 IpsecStartProcess->setEnvironment(*env);
//                 IpsecStartProcess->start(proc, args);
//                 if (!IpsecStartProcess->waitForStarted()) {
//                     if (!IpsecType.contains("strongSwan", Qt::CaseInsensitive)) {
//                         KMessageBox::error(this, i18n("Failed to start \"%1\"." , QString("ipsec setup stop")));
//                         GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("ipsec setup stop")) , KVpncEnum::error);
//                     }
//                     if (! IpsecType.contains("free", Qt::CaseInsensitive) && ((IpsecMajor = 4 && IpsecMinor >= 2 && IpsecSubMinor >= 2)  || IpsecMajor > 4)) {
//                         KMessageBox::error(this, i18n("Failed to start \"%1\"." , QString("ipsec stop")));
//                         GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("ipsec stop")) , KVpncEnum::error);
//                     }
//                 } else {
//                     int tryCounter = 0;
//                     while (IpsecStartProcess != 0 && IpsecStartProcess->state() == QProcess::Running) {
//                         tryCounter++;
// //            if (tryCounter ==50)
//                         {
//                             tryCounter = 0;
//                             if (GlobalConfig->KvpncDebugLevel > 8) {
//                                 if (!IpsecType.contains("strongSwan", Qt::CaseInsensitive))
//                                     GlobalConfig->appendLogEntry(i18n("\"%1\" is still running, waiting for it to terminate..."  , QString("ipsec setup stop")), KVpncEnum::debug);
//                                 if (IpsecType.contains("strongSwan", Qt::CaseInsensitive) && ((IpsecMajor >= 4 && IpsecMinor >= 2 && IpsecSubMinor >= 2) || IpsecMajor > 4))
//                                     GlobalConfig->appendLogEntry(i18n("\"%1\" is still running, waiting for it to terminate..." , QString("ipsec stop")), KVpncEnum::debug);
//                             }
//                         }
// 						usleep(100);
// 						if (GlobalConfig->appPointer->hasPendingEvents())
// 							GlobalConfig->appPointer->processEvents();
//                     }
//
//                 }
//                 disconnect(IpsecStartProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStderr_ipsec()));
//                 disconnect(IpsecStartProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsec()));
//                 //disconnect( IpsecStartProcess, SIGNAL( processExited () ), this, SLOT( removeRouteFreeswan() ) );
//                 delete IpsecStartProcess;
//                 IpsecStartProcess = 0L;


                // stopping using function
                startStopIpsec(true);



                delRouteIpsec();
                removeIptablesFreeswan();
                disconnect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));
                setGuiStatus(KVpncEnum::disconnected);
                durationTimer.stop();
                GlobalConfig->currentConnectRetry = 0;
                connectionEnded();

                if ( GlobalConfig->KvpncDebugLevel > 0 )
                    GlobalConfig->appendLogEntry ( i18n ( "Restoring original ipsec settings" ), KVpncEnum::debug );


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

                if (originalIpsecConfFile.exists()) {
                    if (originalIpsecConfFile.open(QIODevice::ReadOnly)) {
                        originalIpsecConfFileContent = QString(originalIpsecConfFile.readAll());
                        originalIpsecConfFile.close();
                    }
                }

                QFile backupOriginalIpsecConfFile("/etc/ipsec.conf");
                stream.setDevice(&backupOriginalIpsecConfFile);
                if (backupOriginalIpsecConfFile.open(QIODevice::WriteOnly)) {
                    stream << originalIpsecConfFileContent;
                    backupOriginalIpsecConfFile.close();
                }
                stream.setDevice(0);

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

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

                QFile backupOriginalIpsecSecretFile("/etc/ipsec.secrets");
                stream.setDevice(&backupOriginalIpsecSecretFile);
                if (backupOriginalIpsecSecretFile.open(QIODevice::WriteOnly)) {
                    stream << originalIpsecSecretFileContent;
                    backupOriginalIpsecSecretFile.close();
                }
                stream.setDevice(0);


                if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
                    // remove kvpnc entries from secrets file
                    QFile papSecretsFile("/etc/ppp/pap-secrets");
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1" , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                    if (papSecretsFile.open(QIODevice::ReadOnly)) {
                        QString line = "";
                        QString papsecret_content = "";
                        bool kvpnc_start_marker_found = false;
                        bool kvpnc_end_marker_found = false;
                        QStringList contentlist = QString(papSecretsFile.readAll()).split("\n");
                        for (int i = 0; i < contentlist.size(); ++i) {
                            QString line = contentlist.at(i);
                            if (line == "# --- generated by kvpnc. Do not edit it.") {
                                kvpnc_end_marker_found = true;
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("End marker in %1 found"  , QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
                            }
                            if (line == "# +++ generated by kvpnc. Do not edit it.") {
                                kvpnc_start_marker_found = true;
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("Start marker in %1 found" , QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
                            }

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

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


                // start ipsec with restored config again
                startStopIpsec ( false );
            }
            // pptp
            else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp) {

                OldDefaultroute = tmpPath + "default-route." + GlobalConfig->currentProfile->getName(); // default-route.<id>
                if ( PptpProcess != 0) {
                    disconnect(PptpProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_pptp()));
                    disconnect(PptpProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_pptp()));



                    if ( PptpProcess != 0 && PptpProcess->state() == QProcess::Running)
                    {
                        // try to kill the pptp process self
                        PptpProcess->kill();

                        if ( PptpProcess != 0 && PptpProcess->state() == QProcess::Running) {
                            QProcess pptpdKillProcess(this);
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("No pid file, trying to terminate %1 with killall..." , QString("pptp")), KVpncEnum::debug);
                            QString proc = GlobalConfig->pathToKillall;
                            QStringList args;
                            args.append("-TERM");
                            args.append(GlobalConfig->pathToPptp);
                            pptpdKillProcess.setEnvironment(*env);
                            pptpdKillProcess.start(proc, args);
                            if (!pptpdKillProcess.waitForStarted()) {
                                KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , QString(QString(GlobalConfig->pathToKillall + " -TERM " + GlobalConfig->pathToPptp))));
                            } else {
                                if (GlobalConfig->KvpncDebugLevel > 1)
                                    GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString(QString(GlobalConfig->pathToKillall + " -TERM " + GlobalConfig->pathToPptp))) , KVpncEnum::debug);
                                waitForFinished(&pptpdKillProcess, 100);
                            }

                            args.clear();
                            args.append("-KILL");
                            args.append(GlobalConfig->pathToPptp);
                            pptpdKillProcess.setEnvironment(*env);
                            int killcounter=0;
                            while ( PptpProcess != 0 && PptpProcess->state() == QProcess::Running && killcounter < 5 )
                            {
                                pptpdKillProcess.start(proc, args);
                                if (!pptpdKillProcess.waitForStarted()) {
                                    KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , QString(QString(GlobalConfig->pathToKillall + " -KILL " + GlobalConfig->pathToPptp))));
                                } else {
                                    if (GlobalConfig->KvpncDebugLevel > 1)
                                        GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString(QString(GlobalConfig->pathToKillall + " -KILL " + GlobalConfig->pathToPptp))) , KVpncEnum::debug);
                                    waitForFinished(&pptpdKillProcess, 100);
                                }
                                killcounter++;
                            }


                            while (PptpProcess != 0 && PptpProcess->state() == QProcess::Running && killcounter < 25) {
                                killcounter++;
                                if (GlobalConfig->KvpncDebugLevel > 8)
                                    GlobalConfig->appendLogEntry(i18n("\"%1\" is still running, waiting for it to terminate...", QString("pptp")) , KVpncEnum::debug);
                                usleep(100);
                                if (GlobalConfig->appPointer->hasPendingEvents())
                                    GlobalConfig->appPointer->processEvents();
                            }

                            if (killcounter >= 5) {
                                args.clear();
                                args.append("-9");
                                args.append(GlobalConfig->pathToPptp);
                                pptpdKillProcess.setEnvironment(*env);
                                pptpdKillProcess.start(proc, args);
                                if (!pptpdKillProcess.waitForStarted()) {
                                    KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , QString(QString(GlobalConfig->pathToKillall + " -SIGKILL " + GlobalConfig->pathToPptp))));
                                } else {
                                    if (GlobalConfig->KvpncDebugLevel > 1)
                                        GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString(QString(GlobalConfig->pathToKillall + " -SIGKILL " + GlobalConfig->pathToPptp))) , KVpncEnum::debug);

                                    waitForFinished(&pptpdKillProcess, 100);
                                }
                            }
                        }
                    }
                    //why it crash here?
                    //delete PptpProcess;
                    //PptpProcess = 0L;
                }
                durationTimer.stop();

                // write pppd.<profile>.down
                QFile downfile(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".down");
                QTextStream downstream(&downfile);
                if (downfile.open(QIODevice::WriteOnly)) {
                    downstream <<  "#!" << GlobalConfig->InterpreterShell << "\n";
                    downstream << "# generated by kvpnc. Do not edit it." << "\n";
                    downstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
                    /* update dns? */
                    if (GlobalConfig->currentProfile->getUseDnsUpdate()) {
                        //downstream << "chmod u+w  /etc/resolv.conf\n";
                        downstream << "if [ -x /sbin/resolvconf ] ; then\n";
                        downstream << " dev=$1\n";
                        downstream << " if [ -z $dev ] ; then\n";
                        downstream << "  dev=\"ppp0\"\n";
                        downstream << " fi\n";
                        downstream << " /sbin/resolvconf -d $dev\n";

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

                        downstream << "else" << "\n";
                        downstream << "cat " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " > /etc/resolv.conf\n";
                        downstream << "fi" << "\n";
                    } else {
                        /* dont update dns */
                    }

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

// 						if (GlobalConfig->NewDefaultGw != "0.0.0.0") {
// 							QString pppdev = "";
// 							if (!PppdDevice.isEmpty())
// 								pppdev = PppdDevice;
// 							else
// 								pppdev = "ppp0";
//
// 							if (GlobalConfig->KvpncDebugLevel > 3)
// 								GlobalConfig->appendLogEntry(i18n("Removing extra route: %1 over %2 gw %3", QString("0.0.0.0"),  GlobalConfig->NewDefaultGw , QString(pppdev)), KVpncEnum::debug);
// 							downstream << GlobalConfig->pathToIp + " route del 0.0.0.0 via " << GlobalConfig->NewDefaultGw << " dev " << pppdev << "\n";
// 						}
                    }

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

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


                    downfile.close();

                    QProcess pppdDownProcess(this);
                    QString proc = GlobalConfig->InterpreterShell;
                    QStringList args;
                    args.append(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".down");
                    pppdDownProcess.setEnvironment(*env);
                    pppdDownProcess.start(proc, args);
                    if (!pppdDownProcess.waitForStarted()) {
                        KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , QString("PppdDownScript")));
                    } else {
                        if (GlobalConfig->KvpncDebugLevel > 1)
                            GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString("PppdDownScript")) , KVpncEnum::debug);
                        waitForFinished(&pppdDownProcess, 100);

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

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

                        if (GlobalConfig->currentProfile->getUseDnsUpdate() && Utils(GlobalConfig).resolvConfAvailable()) {
                            if (GlobalConfig->KvpncDebugLevel > 1)
                                GlobalConfig->appendLogEntry(i18n("resolvconf restored the old /etc/resolv.conf."), KVpncEnum::debug);
                        } else {
                            if (GlobalConfig->currentProfile->getUseDnsUpdate())
                                if (GlobalConfig->KvpncDebugLevel > 1)
                                    GlobalConfig->appendLogEntry(i18n("/etc/resolv.conf was restored."), KVpncEnum::debug);
                        }
                    }

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

                }

                if (GlobalConfig->currentProfile->getAuthMethod() == "chap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2") {
                    // remove kvpnc entries from chap-secerets
                    QFile ChapSecretsFile("/etc/ppp/chap-secrets");
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1", QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                    if (ChapSecretsFile.open(QIODevice::ReadOnly)) {
                        QString chapsecret_content = "";
                        bool kvpnc_start_marker_found = false;
                        bool kvpnc_end_marker_found = false;
                        QStringList contentlist = QString(ChapSecretsFile.readAll()).split("\n");
                        for (int i = 0; i < contentlist.size(); ++i) {
                            QString line = contentlist.at(i);
                            if (line == "# --- generated by kvpnc. Do not edit it.") {
                                kvpnc_end_marker_found = true;
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("End marker in %1 found" , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                            }
                            if (line == "# +++ generated by kvpnc. Do not edit it.") {
                                kvpnc_start_marker_found = true;
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("Start marker in %1 found" , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                            }

                            if (kvpnc_start_marker_found == false) {
                                chapsecret_content += line;
                                chapsecret_content += '\n';
                            }
                        }
                        ChapSecretsFile.close();
                        if (ChapSecretsFile.remove()) {
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("File %1 successfully removed" , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                            //        ChapSecretsFile.setName("/etc/ppp/chap-secrets2");
                            if (ChapSecretsFile.open(QIODevice::WriteOnly)) {
                                QTextStream stream(&ChapSecretsFile);
                                stream << chapsecret_content;
                                ChapSecretsFile.close();
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("File %1 successfully rewritten" , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                            } else {
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("File %1 rewrite failed" , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
                            }
                        } else {
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("File %1 remove failed" , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
                        }

                    } else {
                        GlobalConfig->appendLogEntry(i18n("File %1 could not be opened." , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
                    }
                }
                if (GlobalConfig->currentProfile->getAuthMethod() == "pap") {
                    // remove kvpnc entries from pap-secerets
                    QFile papSecretsFile("/etc/ppp/pap-secrets");
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1", QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                    if (papSecretsFile.open(QIODevice::ReadOnly)) {
                        QString papsecret_content = "";
                        bool kvpnc_start_marker_found = false;
                        bool kvpnc_end_marker_found = false;
                        QStringList contentlist = QString(papSecretsFile.readAll()).split("\n");
                        for (int i = 0; i < contentlist.size(); ++i) {
                            QString line = contentlist.at(i);
                            if (line == "# --- generated by kvpnc. Do not edit it.") {
                                kvpnc_end_marker_found = true;
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("End marker in %1 found" , QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
                            }
                            if (line == "# +++ generated by kvpnc. Do not edit it.") {
                                kvpnc_start_marker_found = true;
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("Start marker in %1 found" , QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
                            }

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

                    } else {
                        GlobalConfig->appendLogEntry(i18n("File %1 could not be opened." , QString("/etc/ppp/pap-secrets")), KVpncEnum::error);
                    }
                }
                setGuiStatus(KVpncEnum::disconnected);
                GlobalConfig->status = KVpncEnum::disconnected;
                connectCounter = 0;
                disconnect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));
//     connectionEnded();

            }
            // openvpn
            else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn) {
                if (managementhandler != 0) {
                    managementhandler->closeConnection();
                    delete managementhandler;
                    managementhandler = 0L;
                }

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

                if (OpenvpnProcess != 0) {
                    if (OpenvpnProcess->state() == QProcess::Running)
                        OpenvpnProcess->kill();
                    disconnect(OpenvpnProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutput_openvpn()));
                    //disconnect( OpenvpnProcess, SIGNAL( readyReadStandardError() ), this, SLOT( readOutput_openvpn() ) );
                    disconnect(OpenvpnProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(openvpn_exited(int, QProcess::ExitStatus)));
                    delete OpenvpnProcess;
                    OpenvpnProcess = 0L;
                }

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

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

                //     terminateConnection( VtundProcess );
                //     VtundProcess = new QProcess(this);
                //    QString proc =  GlobalConfig->pathToKillall ;
                //    QStringList args;
                //     args.append( "vtund" );
                //
                //     connect( VtundProcess, SIGNAL( readyReadStandardOutput() ), this, SLOT( readFromStdout_disconnect() ) );
                //     connect( VtundProcess, SIGNAL( readyReadStandardError() ), this, SLOT( readFromStderr_disconnect() ) );
                //
                //    DisconnectProcess->setEnvironment(*env);
                //     if ( !DisconnectProcess->start(env) ) {
                //      KMessageBox::sorry( this, i18n( "Failed to start \"%1\"." , QString( "killall vtund" )) );
//        }
//            else
//            {
//             sleep(1);
//            }
//            delete VtundProcess;
//            VtundProcess=0L;

                disconnect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));

                sleep(2);
                delete VtundProcess;
                VtundProcess = 0L;

                connectionEnded();

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

                if (SshProcess != 0 && SshProcess->state() == QProcess::Running) {
                    disconnect(SshProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ssh()));
                    disconnect(SshProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ssh()));
                    disconnect(SshPty, SIGNAL(readyRead()), this, SLOT(readFromPty_ssh()));
                    SshProcess->kill();
                    sleep(1);
                    if (SshProcess->state() == QProcess::Running)
                        SshProcess->kill();
                    sleep(1);
                    if (SshProcess->state() == QProcess::Running)
                        SshProcess->kill();
                    sleep(1);
                    if (SshProcess->state() == QProcess::Running)
                        SshProcess->kill();
                }

                //     terminateConnection( SshProcess );
                //     DisconnectProcess = new QProcess(this);
                //    QString proc = GlobalConfig->pathToKillall; //FIXME: use pid
                //     QStringList args;
                //     args.append( "ssh" );
                //
                //     connect( DisconnectProcess, SIGNAL( readyReadStandardOutput() ), this, SLOT( readFromStdout_disconnect() ) );
                //     connect( DisconnectProcess, SIGNAL( readyReadStandardError() ), this, SLOT( readFromStderr_disconnect() ) );
                //
                //  DisconnectProcess->setEnvironment(*env);
                //  DisconnectProcess->start(proc,args);
                //     if ( !DisconnectProcess->waitForStarted() ) {
                //      KMessageBox::sorry( this, i18n( "Failed to start \"%1\"." , QString( "killall ssh" )) );
                //     }
//            else
//            {
//             sleep(1);
//            }
                if (SshProcess != 0L) {
                    delete SshProcess;
                    SshProcess = 0L;
                }


                // write ssh.<profile>.down
                QFile downfile(tmpPath + "ssh." + GlobalConfig->currentProfile->getName() + ".down");
                QTextStream downstream(&downfile);
                if (downfile.open(QIODevice::WriteOnly)) {
                    downstream <<  "#!" << GlobalConfig->InterpreterShell << "\n";
                    downstream << "# generated by kvpnc. Do not edit it." << "\n";
                    /* update dns? */
                    if (GlobalConfig->currentProfile->getUseDnsUpdate()) {
                        downstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
//       downstream << "chmod u+w  /etc/resolv.conf\n";
                        downstream << "if [ -x /sbin/resolvconf ] ; then\n";
                        downstream << " dev=$1\n";
                        downstream << " if [ -z $dev ] ; then\n";
                        if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tun")
                            downstream << "  dev=\"tun0\"\n";
                        else
                            downstream << "  dev=\"tap0\"\n";
                        downstream << " fi\n";
                        downstream << " /sbin/resolvconf -d $dev\n";
                        downstream << "else" << "\n";
                        downstream << "cat " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " > /etc/resolv.conf\n";
                        downstream << "fi" << "\n";
                    } else {
                        /* dont update dns */
                    }

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

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

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

                    }

//                     if (GlobalConfig->NewDefaultGw != "0.0.0.0") {
//                         SshDevice = "";
// //       if ( !PppDevice.isEmpty() )
// //        sshev = PppDevice;
// //       else
//                         if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tun")
//                             SshDevice = "tun0";
//                         else
//                             SshDevice = "tap0";
//
//                         if (GlobalConfig->KvpncDebugLevel > 3)
//                             GlobalConfig->appendLogEntry(i18n("Removing extra route: %1 over %2 gw %3" , QString("0.0.0.0"),  GlobalConfig->NewDefaultGw , SshDevice), KVpncEnum::debug);
//                         downstream << GlobalConfig->pathToIp + " route del 0.0.0.0 via " << GlobalConfig->NewDefaultGw << " dev " << SshDevice << "\n";
//                     }

                    downfile.close();

                    QProcess SshDownProcess(this);
                    QString proc = GlobalConfig->InterpreterShell;
                    QStringList args;
                    args.append(tmpPath + "ssh." + GlobalConfig->currentProfile->getName() + ".down");
                    SshDownProcess.setEnvironment(*env);
                    SshDownProcess.start(proc, args);
                    if (!SshDownProcess.waitForStarted()) {
                        KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , QString("SshDownScript")));
                    } else {
                        if (GlobalConfig->KvpncDebugLevel > 1)
                            GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString("SshDownScript")) , KVpncEnum::debug);
                        waitForFinished(&SshDownProcess, 100);

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

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

                        if (GlobalConfig->currentProfile->getUseDnsUpdate() && Utils(GlobalConfig).resolvConfAvailable()) {
                            if (GlobalConfig->KvpncDebugLevel > 1)
                                GlobalConfig->appendLogEntry(i18n("resolvconf restored the old /etc/resolv.conf."), KVpncEnum::debug);
                        } else {
                            if (GlobalConfig->currentProfile->getUseDnsUpdate())
                                if (GlobalConfig->KvpncDebugLevel > 1)
                                    GlobalConfig->appendLogEntry(i18n("/etc/resolv.conf was restored."), KVpncEnum::debug);
                        }
                    }
                } else {
                    GlobalConfig->appendLogEntry(i18n("\"%1\" could not be written." , QString(i18n("ssh down file"))) , KVpncEnum::error);

                }


                disconnect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));
                connectionEnded();
            }
            // l2tpd_plain
            else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_plain)
            {

// 					if (QFile("/var/run/l2tpd.pid").exists()) {
// 						if (GlobalConfig->KvpncDebugLevel > 1)
// 							GlobalConfig->appendLogEntry(i18n("Using control interface for disconnecting l2tp connection"),KVpncEnum::debug);
// 						QFile L2tpdControlFile ( "/var/run/l2tp-control" );
// 						QTextStream stream( &L2tpdControlFile );
// 						if ( L2tpdControlFile.open( IO_WriteOnly  ) ) {
// 							stream << "d " << GlobalConfig->currentProfile->getName() << "\n";
// 							L2tpdControlFile.close();
// 						}
// 					} else {
                if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd ) {
                    if (L2tpdProcess->state() == QProcess::Running) {
                        disconnect(this, SIGNAL(L2tpdStdoutRecieved()), this, SLOT(processStdout_l2tpd()));
                        disconnect(this, SIGNAL(L2tpdStderrRecieved()), this, SLOT(processStderr_l2tpd()));
                        L2tpdProcess->kill();
                        if (L2tpdProcess != 0L && L2tpdProcess->state() == QProcess::Running)
                            L2tpdProcess->terminate();
                        sleep(1);
                        if (L2tpdProcess != NULL  && L2tpdProcess->state() == QProcess::Running)
                            L2tpdProcess->kill();
                    }
                }
                if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp ) {
                    if ( OpenL2tpProcess != 0L && OpenL2tpProcess->state() == QProcess::Running ) {

                        if (OpenL2tpProcess != 0L && OpenL2tpProcess->state() == QProcess::Running) {

                            disconnect(OpenL2tpProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_openl2tp()));
                            disconnect(OpenL2tpProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_openl2tp()));

                            OpenL2tpProcess->kill();

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

                        if ( !Utils ( GlobalConfig, parent ).unloadKernelModule ( "slhc", parent ) ) {
                            if ( GlobalConfig->KvpncDebugLevel > 3 )
                                GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed", QString("slhc") ), KVpncEnum::debug );
                        } else {
                            if ( GlobalConfig->KvpncDebugLevel > 3 )
                                GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeeded", QString("slhc") ), KVpncEnum::debug );
                        }
                        if ( !Utils ( GlobalConfig, parent ).unloadKernelModule ( "ppp_generic", parent ) ) {
                            if ( GlobalConfig->KvpncDebugLevel > 3 )
                                GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed.", QString("ppp_generic") ), KVpncEnum::debug );
                        } else {
                            if ( GlobalConfig->KvpncDebugLevel > 3 )
                                GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeeded", QString("ppp_generic") ), KVpncEnum::debug );
                        }
                        if ( !Utils ( GlobalConfig, parent ).unloadKernelModule ( "pppox", parent ) ) {
                            if ( GlobalConfig->KvpncDebugLevel > 3 )
                                GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed.", QString("pppox") ), KVpncEnum::debug );
                        } else {
                            if ( GlobalConfig->KvpncDebugLevel > 3 )
                                GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeeded", QString("pppox") ), KVpncEnum::debug );
                        }
                        if ( !Utils ( GlobalConfig, parent ).unloadKernelModule ( "pppol2tp", parent ,true ) ) {
                            if ( GlobalConfig->KvpncDebugLevel > 3 )
                                GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed", QString("pppol2tp") ), KVpncEnum::debug );
                        } else {
                            if ( GlobalConfig->KvpncDebugLevel > 3 )
                                GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeeded", QString("pppol2tp") ), KVpncEnum::debug );
                        }

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

                    }
                }
// 					}



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

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

                        } else {
                            GlobalConfig->appendLogEntry ( i18n ( "File %1 could not opened!", QString("/etc/ppp/chap-secrets") ), KVpncEnum::error );
                        }
                    }
                    if ( GlobalConfig->currentProfile->getAuthMethod() == "pap" ) {
                        // remove kvpnc entries from pap-secerets
                        QFile papSecretsFile ( "/etc/ppp/pap-secrets" );
                        if ( GlobalConfig->KvpncDebugLevel > 0 )
                            GlobalConfig->appendLogEntry ( i18n ( "pppd secrets file: %1", QString("/etc/ppp/chap-secrets") ), KVpncEnum::debug );
                        QTextStream stream ( &papSecretsFile );
                        if ( papSecretsFile.open ( IO_ReadOnly ) ) {
                            QString line = "";
                            QString papsecret_content = "";
                            bool kvpnc_start_marker_found = false;
                            bool kvpnc_end_marker_found = false;
                            while ( !stream.atEnd() ) {
                                line = stream.readLine(); // line of text excluding '\n'
                                if ( line == "# --- generated by kvpnc. Do not edit it." ) {
                                    kvpnc_end_marker_found = true;
                                    if ( GlobalConfig->KvpncDebugLevel > 2 )
                                        GlobalConfig->appendLogEntry ( i18n ( "End marker in %1 found", QString("/etc/ppp/pap-secrets") ), KVpncEnum::debug );
                                }
                                if ( line == "# +++ generated by kvpnc. Do not edit it." ) {
                                    kvpnc_start_marker_found = true;
                                    if ( GlobalConfig->KvpncDebugLevel > 2 )
                                        GlobalConfig->appendLogEntry ( i18n ( "Start marker in %1 found", QString("/etc/ppp/pap-secrets") ), KVpncEnum::debug );
                                }

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

                        } else {
                            GlobalConfig->appendLogEntry ( i18n ( "File %1 could not opened!", QString("/etc/ppp/pap-secrets") ), KVpncEnum::error );
                        }
                    }
                    // remove kvpnc entries from /etc/l2tpd/l2tp-secrets
                    QFile L2tpSecretsFile ( "/etc/l2tpd/l2tp-secrets" );
                    if ( GlobalConfig->KvpncDebugLevel > 0 )
                        GlobalConfig->appendLogEntry ( i18n ( "l2tpd secrets file: %1", QString("/etc/l2tpd/l2tp-secrets") ), KVpncEnum::debug );
                    QTextStream stream ( &L2tpSecretsFile );
                    if ( L2tpSecretsFile.open ( IO_ReadOnly ) ) {
                        QString line = "";
                        QString l2tpsecret_content = "";
                        bool kvpnc_start_marker_found = false;
                        bool kvpnc_end_marker_found = false;
                        while ( !stream.atEnd() ) {
                            line = stream.readLine(); // line of text excluding '\n'
                            if ( line == "# --- generated by kvpnc. Do not edit it." ) {
                                kvpnc_end_marker_found = true;
                                if ( GlobalConfig->KvpncDebugLevel > 2 )
                                    GlobalConfig->appendLogEntry ( i18n ( "End marker in %1 found", QString("/etc/l2tpd/l2tp-secrets") ), KVpncEnum::debug );
                            }
                            if ( line == "# +++ generated by kvpnc. Do not edit it." ) {
                                kvpnc_start_marker_found = true;
                                if ( GlobalConfig->KvpncDebugLevel > 2 )
                                    GlobalConfig->appendLogEntry ( i18n ( "Start marker in %1 found", QString("/etc/l2tpd/l2tp-secrets") ), KVpncEnum::debug );
                            }

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

                    } else {
                        GlobalConfig->appendLogEntry ( i18n ( "File %1 could not opened!", QString("/etc/l2tpd/l2tp-secrets") ), KVpncEnum::error );
                    }
                }

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



        }
        //   ConnectingProcess = 0L;

        setGuiStatus(KVpncEnum::disconnected);

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

    } else if (GlobalConfig->status == KVpncEnum::connecting) {
        prevConnectionState = KVpncEnum::connecting;
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("Disconnect requested, status connecting"), KVpncEnum::debug);

        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("Killing process while connecting.\n"), KVpncEnum::debug);



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

                tmpPath = KStandardDirs::locateLocal("data", "kvpnc/");
                //Vpnc_pid_file = tmpPath + "vpnc-pid." + GlobalConfig->currentProfile->getID() + ".pid"; // vpnc-pid.<id>.pid
                VpncDisconnectScript = tmpPath + "vpnc-disconnect." + GlobalConfig->currentProfile->getID() + ".sh";
                // write vpnc connect script
                QFile pidFile(GlobalConfig->Vpnc_pid_file);
                QString Vpnc_pid = "";
                if (pidFile.open(QIODevice::ReadOnly)) {
                    Vpnc_pid = QString(pidFile.readAll()).trimmed();
                }

                if ( VpncProcess != 0 ) {
                    if ( VpncProcess->state() == QProcess::Running ) {
                        disconnect(VpncProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutputFrom_vpnc()));

                        VpncProcess->kill();
                        sleep ( 1 );
                        if ( VpncProcess->state() == QProcess::Running ) {
                            VpncProcess->kill();
                            sleep ( 1 );
                        }
                        if ( VpncProcess->state() == QProcess::Running ) {
                            VpncProcess->kill();
                            sleep ( 1 );
                        }
                        if ( VpncProcess->state() == QProcess::Running )
                            VpncProcess->kill();
                    }
                    delete VpncProcess;
                    VpncProcess = 0L;
                }



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

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

                    if ( GlobalConfig->currentProfile->getUseDnsUpdate() ) {
                        // FIXME this is a temporary fix for not calling vpnc script with disconnect at disconnect time!
                        if (VpncDevice.isEmpty())
                            VpncDevice = "tun0";
                        stream << "    if [ -f /sbin/resolvconf ] ; then\n";
                        stream << "        /sbin/resolvconf -d \"" << VpncDevice <<  "\"\n";
                        stream << "    else\n";
                        stream << "        cat " + tmpPath + "resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() + " > /etc/resolv.conf\n";
                        stream << "    fi\n";
                        // end temp fix
                    } else {
                        /* dont update dns */
                    }

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

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

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

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

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

                    file.close();

                    DisconnectProcess = new QProcess(this);
                    QString proc = GlobalConfig->InterpreterShell;
                    QStringList args;
                    args.append(VpncDisconnectScript);

                    connect(DisconnectProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_disconnect()));
                    connect(DisconnectProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_disconnect()));

                    DisconnectProcess->start(proc, args);
                    if (!DisconnectProcess->waitForStarted()) {
                        KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , QString("vpnc_disconnect")));
                    } else {
                        waitForFinished(DisconnectProcess, 100);
                    }
                    disconnect(DisconnectProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_disconnect()));
                    disconnect(DisconnectProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_disconnect()));
                    delete DisconnectProcess;
                    DisconnectProcess = 0L;
                }

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

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

        } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig) {
            if (CiscoVpncProcess != 0 && CiscoVpncProcess->state() == QProcess::Running) {
                CiscoVpncProcess->kill();
                QTimer::singleShot(5000, CiscoVpncProcess, SLOT(kill()));
                sleep(5);
                delete CiscoVpncProcess;
                CiscoVpncProcess = 0L;
            }
        } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {

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

            if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
//      if (QFile("/var/run/l2tpd.pid").exists())
//      {
//       if (GlobalConfig->KvpncDebugLevel > 1)
//        GlobalConfig->appendLogEntry(i18n("Using control interface for disconnecting l2tp connection"),KVpncEnum::debug);
//       QFile L2tpdControlFile ( "/var/run/l2tp-control" );
//       QTextStream stream( &L2tpdControlFile );
//       if ( L2tpdControlFile.open( QIODevice::WriteOnly  ) ) {
//        stream << "d " << GlobalConfig->currentProfile->getName() << "\n";
//        L2tpdControlFile.close();
//       }
                //     }
//      else
                {
                    if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd) {
                        if (L2tpdProcess != 0L && L2tpdProcess->state() == QProcess::Running) {
                            L2tpWaitForPppUpTimer.stop();
                            disconnect(this, SIGNAL(L2tpdStdoutRecieved()), this, SLOT(processStdout_l2tpd()));
                            disconnect(this, SIGNAL(L2tpdStderrRecieved()), this, SLOT(processStderr_l2tpd()));

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

                                disconnect(OpenL2tpProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_openl2tp()));
                                disconnect(OpenL2tpProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_openl2tp()));

                                OpenL2tpProcess->kill();

                                delete OpenL2tpProcess;
                                OpenL2tpProcess = 0L;

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

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

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


                    }
                }
            }

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

            if (GlobalConfig->currentProfile->getUseLeftSourceIp()) {
                if ( GlobalConfig->KvpncDebugLevel > 3 )
                    GlobalConfig->appendLogEntry ( i18n ( "Removing virtual IP address" ), KVpncEnum::debug );
                doAddRemoveVirtualIp("del");
            }



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

            putenv((char*)("LC_ALL=C"));
            IpsecWhackDeleteProcess = new QProcess(this);
            QString proc = GlobalConfig->pathToIpsec;
            QStringList args;
            args.append("whack");
            args.append("--name");
            args.append(GlobalConfig->currentProfile->getName());
            args.append("--delete");

            connect(IpsecWhackDeleteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhackdelete()));
            connect(IpsecWhackDeleteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhackdelete()));

            IpsecWhackDeleteProcess->setEnvironment(*env);
            IpsecWhackDeleteProcess->start(proc, args);
            if (!IpsecWhackDeleteProcess->waitForStarted()) {
                KMessageBox::error(this, i18n("Failed to start \"%1\"." , QString(GlobalConfig->pathToIpsec + " whack' --name " + GlobalConfig->currentProfile->getName() + " --delete")));
                GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString(GlobalConfig->pathToIpsec + " whack' --name " + GlobalConfig->currentProfile->getName() + " --delete")) , KVpncEnum::error);
            } else {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("\"%1\" started.", QString(GlobalConfig->pathToIpsec + " whack --name " + GlobalConfig->currentProfile->getName() + " --delete")), KVpncEnum::debug);

//                 int tryCounter = 0;
//                 while (IpsecWhackDeleteProcess != 0 && IpsecWhackDeleteProcess->state() == QProcess::Running) {
//                     tryCounter++;
//                     if (tryCounter == 20) {
//                         tryCounter = 0;
//                         if (GlobalConfig->KvpncDebugLevel > 8)
//                             GlobalConfig->appendLogEntry(i18n("\"%1\" is still running, waiting for it to terminate..." , QString(GlobalConfig->pathToIpsec + " whack --name " + GlobalConfig->currentProfile->getName() + " --delete")), KVpncEnum::debug);
//                     }
//                     usleep(500);
//                 }
                waitForFinished(IpsecWhackDeleteProcess, 100);
            }
            disconnect(IpsecWhackDeleteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhackdelete()));
            disconnect(IpsecWhackDeleteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhackdelete()));
            delete IpsecWhackDeleteProcess;
            IpsecWhackDeleteProcess = 0L;

            IpsecStartProcess = new QProcess(this);
            proc = GlobalConfig->pathToIpsec;
            args.clear();
            if (!IpsecType.contains("strongSwan", Qt::CaseInsensitive)) {
                args.append("setup");
                args.append("stop");
            }
            if (! IpsecType.contains("free", Qt::CaseInsensitive) && ((IpsecMajor = 4 && IpsecMinor >= 2 && IpsecSubMinor >= 2)  || IpsecMajor > 4)) {
                args.append("stop");
            }
            IpsecStartProcess->setEnvironment(*env);

            connect(IpsecStartProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStderr_ipsec()));
            connect(IpsecStartProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsec()));
            //connect( IpsecStartProcess, SIGNAL( processExited () ), this, SLOT( removeRouteFreeswan() ) );

            IpsecStartProcess->start(proc, args);
            if (!IpsecStartProcess->waitForStarted()) {
                if (!IpsecType.contains("strongSwan", Qt::CaseInsensitive)) {
                    KMessageBox::error(this, i18n("Failed to start \"%1\"." , QString("ipsec setup stop")));
                    GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("ipsec setup stop")) , KVpncEnum::error);
                }
                if (! IpsecType.contains("free", Qt::CaseInsensitive) && ((IpsecMajor = 4 && IpsecMinor >= 2 && IpsecSubMinor >= 2)  || IpsecMajor > 4)) {
                    KMessageBox::error(this, i18n("Failed to start \"%1\"." , QString("ipsec stop")));
                    GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("ipsec stop")) , KVpncEnum::error);
                }
            } else {
//                 int tryCounter = 0;
//     while (IpsecStartProcess != 0L && IpsecStartProcess->state() == QProcess::Running) {
//                     tryCounter++;
//                     if (tryCounter == 20) {
//                         tryCounter = 0;
//                         if (GlobalConfig->KvpncDebugLevel > 8) {
//        if (!IpsecType.contains("strongSwan", Qt::CaseInsensitive))
//                                 GlobalConfig->appendLogEntry(i18n("\"%1\" is still running, waiting for it to terminate..." , QString("ipsec setup stop")), KVpncEnum::debug);
//        if (IpsecType.contains("strongSwan", Qt::CaseInsensitive) && ((IpsecMajor >= 4 && IpsecMinor >= 2 && IpsecSubMinor >= 2) || IpsecMajor > 4))
//                                 GlobalConfig->appendLogEntry(i18n("\"%1\" is still running, waiting for it to terminate...", QString("ipsec stop")), KVpncEnum::debug);
//                         }
//                     }
//                     usleep(100);
//                 }
                waitForFinished(IpsecStartProcess, 100);
            }
            disconnect(IpsecStartProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStderr_ipsec()));
            disconnect(IpsecStartProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsec()));
            //disconnect( IpsecStartProcess, SIGNAL( processExited () ), this, SLOT( removeRouteFreeswan() ) );
            delete IpsecStartProcess;
            IpsecStartProcess = 0L;

//    delRouteIpsec();
            removeIptablesFreeswan();
            setGuiStatus(KVpncEnum::disconnected);

            GlobalConfig->currentConnectRetry = 0;

            connectionEnded();


            if ( GlobalConfig->KvpncDebugLevel > 0 )
                GlobalConfig->appendLogEntry ( i18n ( "Restoring original ipsec settings" ), KVpncEnum::debug );


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

            if (originalIpsecConfFile.exists()) {
                if (originalIpsecConfFile.open(QIODevice::ReadOnly)) {
                    originalIpsecConfFileContent = QString(originalIpsecConfFile.readAll());
                    originalIpsecConfFile.close();
                }
            }

            QFile backupOriginalIpsecConfFile("/etc/ipsec.conf");
            stream.setDevice(&backupOriginalIpsecConfFile);
            if (backupOriginalIpsecConfFile.open(QIODevice::WriteOnly)) {
                stream << originalIpsecConfFileContent;
                backupOriginalIpsecConfFile.close();
            }
            stream.setDevice(0);

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

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

            QFile backupOriginalIpsecSecretFile("/etc/ipsec.secrets");
            stream.setDevice(&backupOriginalIpsecSecretFile);
            if (backupOriginalIpsecSecretFile.open(QIODevice::WriteOnly)) {
                stream << originalIpsecSecretFileContent;
                backupOriginalIpsecSecretFile.close();
            }
            stream.setDevice(0);

            if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
                if (GlobalConfig->currentProfile->getAuthMethod() == "chap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2") {
                    // remove kvpnc entries from chap-secerets
                    QFile ChapSecretsFile("/etc/ppp/chap-secrets");
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1", QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                    if (ChapSecretsFile.open(QIODevice::ReadOnly)) {
                        QString chapsecret_content = "";
                        bool kvpnc_start_marker_found = false;
                        bool kvpnc_end_marker_found = false;
                        QStringList contentlist = QString(ChapSecretsFile.readAll()).split("\n");
                        for (int i = 0; i < contentlist.size(); ++i) {
                            QString line = contentlist.at(i);
                            if (line == "# --- generated by kvpnc. Do not edit it.") {
                                kvpnc_end_marker_found = true;
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("End marker in %1 found"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                            }
                            if (line == "# +++ generated by kvpnc. Do not edit it.") {
                                kvpnc_start_marker_found = true;
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("Start marker in %1 found"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                            }

                            if (kvpnc_start_marker_found == false) {
                                chapsecret_content += line;
                                chapsecret_content += '\n';
                            }
                        }
                        ChapSecretsFile.close();
                        if (ChapSecretsFile.remove()) {
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("File %1 successfully removed"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                            //        ChapSecretsFile.setName("/etc/ppp/chap-secrets2");
                            if (ChapSecretsFile.open(QIODevice::WriteOnly)) {
                                stream.setDevice(&ChapSecretsFile);
                                stream << chapsecret_content;
                                ChapSecretsFile.close();
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("File %1 successfully rewritten"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                            } else {
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("File %1 rewrite failed"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
                            }
                        } else {
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("File %1 remove failed"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
                        }

                    } else {
                        GlobalConfig->appendLogEntry(i18n("File %1 could not be opened."  , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
                    }
                }
                if (GlobalConfig->currentProfile->getAuthMethod() == "pap") {
                    // remove kvpnc entries from pap-secerets
                    QFile papSecretsFile("/etc/ppp/pap-secrets");
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1", QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                    if (papSecretsFile.open(QIODevice::ReadOnly)) {
                        QString papsecret_content = "";
                        bool kvpnc_start_marker_found = false;
                        bool kvpnc_end_marker_found = false;
                        QStringList contentlist = QString(papSecretsFile.readAll()).split("\n");
                        for (int i = 0; i < contentlist.size(); ++i) {
                            QString line = contentlist.at(i);
                            if (line == "# --- generated by kvpnc. Do not edit it.") {
                                kvpnc_end_marker_found = true;
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("End marker in %1 found"  , QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
                            }
                            if (line == "# +++ generated by kvpnc. Do not edit it.") {
                                kvpnc_start_marker_found = true;
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("Start marker in %1 found"  , QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
                            }

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

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

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

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

            QFile file2(tmpPath + "setkey." + GlobalConfig->currentProfile->getName() + ".remove_setkey.sh");
            QTextStream stream2(&file2);
            if (file2.open(QIODevice::WriteOnly)) {
                stream2 <<  "#!" << GlobalConfig->InterpreterShell << "\n";
                stream2 << "# generated by kvpnc. Do not edit it." << "\n";
                stream2 << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";
                stream2 << GlobalConfig->pathToSetkey << " -PF" << "\n";
                stream2 << GlobalConfig->pathToSetkey << " -F" << "\n";
                file2.close();
                if (GlobalConfig->KvpncDebugLevel > 1)
                    GlobalConfig->appendLogEntry(i18n("\"%1\" write successful." , QString("setkey (remove)")) , KVpncEnum::debug);
            } else {
                //      KMessageBox::error( this, i18n( "\"%1\" write failed." , QString( "setkey (remove)" )) );
                GlobalConfig->appendLogEntry(i18n("\"%1\" write failed." , QString("setkey (remove)")) , KVpncEnum::error);
            }

            if (RacoonctlProcess != 0 && RacoonctlProcess->state() == QProcess::Running) {
                disconnect(RacoonctlProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_racoonctl()));
                disconnect(RacoonctlProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_racoonctl()));
                RacoonctlProcess->kill();
            }
            if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon) {
                //if (QFile("/var/run/l2tpd.pid").exists())
                //{
                // if (GlobalConfig->KvpncDebugLevel > 1)
                //  GlobalConfig->appendLogEntry(i18n("Using control interface for disconnecting l2tp connection"),KVpncEnum::debug);
                // QFile L2tpdControlFile ( "/var/run/l2tp-control" );
                // QTextStream stream( &L2tpdControlFile );
                // if ( L2tpdControlFile.open( QIODevice::WriteOnly  ) ) {
                //  stream << "d " << GlobalConfig->currentProfile->getName() << "\n";
                //  L2tpdControlFile.close();
                // }
                //}
                //else
                //{
                // if (QFile("/var/run/l2tpd.pid").exists())
                // {
                //  if (GlobalConfig->KvpncDebugLevel > 1)
                //   GlobalConfig->appendLogEntry(i18n("Using control interface for disconnecting l2tp connection"),KVpncEnum::debug);
                //  QFile L2tpdControlFile ( "/var/run/l2tp-control" );
                //  QTextStream stream( &L2tpdControlFile );
                //  if ( L2tpdControlFile.open( QIODevice::WriteOnly  ) ) {
                //   stream << "d " << GlobalConfig->currentProfile->getName() << "\n";
                //   L2tpdControlFile.close();
                //  }
                //  else
                //  {
                if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd) {
                    if (L2tpdProcess != 0L && L2tpdProcess->state() == QProcess::Running) {

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

                        L2tpdProcess->kill();
                        if (L2tpdProcess->state() == QProcess::Running)
                            L2tpdProcess->terminate();
                        sleep(1);
                        if (L2tpdProcess != 0L  && L2tpdProcess->state() == QProcess::Running)
                            L2tpdProcess->kill();
                    }
                }
                if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp) {
                    if (OpenL2tpProcess != 0L) {
                        if (OpenL2tpProcess->state() == QProcess::Running) {
                            disconnect(OpenL2tpProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_openl2tp()));
                            disconnect(OpenL2tpProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_openl2tp()));
                            OpenL2tpProcess->kill();

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

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

                //}
                //}
                //}

            }

            if (RacoonTailProcess != 0 && RacoonTailProcess->state() == QProcess::Running) {
                disconnect(RacoonTailProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_tail_racoon()));
                disconnect(RacoonTailProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_tail_racoon()));
                //      terminateConnection( RacoonTailProcess );
                RacoonTailProcess->kill();
                if (GlobalConfig->KvpncDebugLevel > 2)
                    GlobalConfig->appendLogEntry(i18n("Killing \"%1\"..." , QString("racoon tail")) , KVpncEnum::debug);
            }

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


            if (racoon_tunnel_state == 1) {
                if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon && GlobalConfig->currentProfile->getUseLeftSourceIp()) {
                    if ( GlobalConfig->KvpncDebugLevel > 3 )
                        GlobalConfig->appendLogEntry ( i18n ( "Removing virtual IP address" ), KVpncEnum::debug );
                    doAddRemoveVirtualIp("del");
                }
                stopRacoon();
            }

            else {
                if (RacoonctlProcess != 0L) {
                    if (RacoonctlProcess->state() == QProcess::Running)
                        RacoonctlProcess->kill();
                }
            }

            if (RacoonProcess != 0 && RacoonProcess->state() == QProcess::Running) {
                //     disconnect ( RacoonProcess, SIGNAL ( readyReadStandardOutput() ), this, SLOT ( readFromStdout_racoon() ) );
                //     disconnect ( RacoonProcess, SIGNAL ( readyReadStandardError() ), this, SLOT ( readFromStderr_racoon() ) );

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

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

            if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon && (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd ||  GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd)) {
                if (GlobalConfig->currentProfile->getAuthMethod() == "chap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2") {
                    // remove kvpnc entries from chap-secerets
                    QFile ChapSecretsFile("/etc/ppp/chap-secrets");
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1", QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                    if (ChapSecretsFile.open(QIODevice::ReadOnly)) {
                        QString chapsecret_content = "";
                        bool kvpnc_start_marker_found = false;
                        bool kvpnc_end_marker_found = false;
                        QStringList contentlist = QString(ChapSecretsFile.readAll()).split("\n");
                        for (int i = 0; i < contentlist.size(); ++i) {
                            QString line = contentlist.at(i);
                            if (line == "# --- generated by kvpnc. Do not edit it.") {
                                kvpnc_end_marker_found = true;
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("End marker in %1 found"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                            }
                            if (line == "# +++ generated by kvpnc. Do not edit it.") {
                                kvpnc_start_marker_found = true;
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("Start marker in %1 found"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                            }

                            if (kvpnc_start_marker_found == false) {
                                chapsecret_content += line;
                                chapsecret_content += '\n';
                            }
                        }
                        ChapSecretsFile.close();
                        if (ChapSecretsFile.remove()) {
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("File %1 successfully removed"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                            //        ChapSecretsFile.setName("/etc/ppp/chap-secrets2");
                            if (ChapSecretsFile.open(QIODevice::WriteOnly)) {
                                QTextStream stream(&ChapSecretsFile);
                                stream << chapsecret_content;
                                ChapSecretsFile.close();
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("File %1 successfully rewritten"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                            } else {
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("File %1 rewrite failed"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
                            }
                        } else {
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("File %1 remove failed"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
                        }

                    } else {
                        GlobalConfig->appendLogEntry(i18n("File %1 could not be opened."  , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
                    }
                }
                if (GlobalConfig->currentProfile->getAuthMethod() == "pap") {
                    // remove kvpnc entries from pap-secerets
                    QFile papSecretsFile("/etc/ppp/pap-secrets");
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1", QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                    if (papSecretsFile.open(QIODevice::ReadOnly)) {
                        QString papsecret_content = "";
                        bool kvpnc_start_marker_found = false;
                        bool kvpnc_end_marker_found = false;
                        QStringList contentlist = QString(papSecretsFile.readAll()).split("\n");
                        for (int i = 0; i < contentlist.size(); ++i) {
                            QString line = contentlist.at(i);
                            if (line == "# --- generated by kvpnc. Do not edit it.") {
                                kvpnc_end_marker_found = true;
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("End marker in %1 found"  , QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
                            }
                            if (line == "# +++ generated by kvpnc. Do not edit it.") {
                                kvpnc_start_marker_found = true;
                                if (GlobalConfig->KvpncDebugLevel > 2)
                                    GlobalConfig->appendLogEntry(i18n("Start marker in %1 found"  , QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
                            }

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

                    } else {
                        GlobalConfig->appendLogEntry(i18n("File %1 could not be opened."  , QString("/etc/ppp/pap-secrets")), KVpncEnum::error);
                    }
                }
            }
        } else if (ConnectingProcess == VpnAccountData::pptp) {
            disconnect(PptpProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_pptp()));
            disconnect(PptpProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_pptp()));

            if ( PptpProcess != 0 && PptpProcess->state() == QProcess::Running)
            {
                // try to kill the pptp process self
                PptpProcess->kill();

                if ( PptpProcess != 0 && PptpProcess->state() == QProcess::Running) {
                    QProcess pptpdKillProcess(this);
                    if (GlobalConfig->KvpncDebugLevel > 2)
                        GlobalConfig->appendLogEntry(i18n("No pid file, trying to terminate %1 with killall..." , QString("pptp")), KVpncEnum::debug);
                    QString proc = GlobalConfig->pathToKillall;
                    QStringList args;
                    args.append("-TERM");
                    args.append(GlobalConfig->pathToPptp);
                    pptpdKillProcess.setEnvironment(*env);
                    pptpdKillProcess.start(proc, args);
                    if (!pptpdKillProcess.waitForStarted()) {
                        KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , QString(QString(GlobalConfig->pathToKillall + " -TERM " + GlobalConfig->pathToPptp))));
                    } else {
                        if (GlobalConfig->KvpncDebugLevel > 1)
                            GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString(QString(GlobalConfig->pathToKillall + " -TERM " + GlobalConfig->pathToPptp))) , KVpncEnum::debug);
                        waitForFinished(&pptpdKillProcess, 100);
                    }

                    args.clear();
                    args.append("-KILL");
                    args.append(GlobalConfig->pathToPptp);
                    pptpdKillProcess.setEnvironment(*env);
                    int killcounter=0;
                    while ( PptpProcess != 0 && PptpProcess->state() == QProcess::Running && killcounter < 5 )
                    {
                        killcounter++;
                        pptpdKillProcess.start(proc, args);
                        if (!pptpdKillProcess.waitForStarted()) {
                            KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , QString(QString(GlobalConfig->pathToKillall + " -KILL " + GlobalConfig->pathToPptp))));
                        } else {
                            if (GlobalConfig->KvpncDebugLevel > 1)
                                GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString(QString(GlobalConfig->pathToKillall + " -KILL " + GlobalConfig->pathToPptp))) , KVpncEnum::debug);
                            waitForFinished(&pptpdKillProcess, 100);
                        }
                    }


                    while (PptpProcess != 0 && PptpProcess->state() == QProcess::Running && killcounter < 25) {
                        killcounter++;
                        if (GlobalConfig->KvpncDebugLevel > 8)
                            GlobalConfig->appendLogEntry(i18n("\"%1\" is still running, waiting for it to terminate...", QString("pptp")) , KVpncEnum::debug);
                        usleep(100);
                        if (GlobalConfig->appPointer->hasPendingEvents())
                            GlobalConfig->appPointer->processEvents();
                    }

                    if (killcounter >= 5) {
                        args.clear();
                        args.append("-9");
                        args.append(GlobalConfig->pathToPptp);
                        pptpdKillProcess.setEnvironment(*env);
                        pptpdKillProcess.start(proc, args);
                        if (!pptpdKillProcess.waitForStarted()) {
                            KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , QString(QString(GlobalConfig->pathToKillall + " -SIGKILL " + GlobalConfig->pathToPptp))));
                        } else {
                            if (GlobalConfig->KvpncDebugLevel > 1)
                                GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString(QString(GlobalConfig->pathToKillall + " -SIGKILL " + GlobalConfig->pathToPptp))) , KVpncEnum::debug);

                            waitForFinished(&pptpdKillProcess, 100);
                        }
                    }
                }
            }
            delete PptpProcess;
            PptpProcess = 0L;

            // write pppd.<profile>.down
            QFile downfile(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".down");
            QTextStream downstream(&downfile);
            if (downfile.open(QIODevice::WriteOnly)) {
                downstream <<  "#!" << GlobalConfig->InterpreterShell << "\n";
                downstream << "# generated by kvpnc. Do not edit it." << "\n";
                downstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
                /* update dns? */
                if (GlobalConfig->currentProfile->getUseDnsUpdate()) {
                    //downstream << "chmod u+w  /etc/resolv.conf\n";
                    downstream << "if [ -x /sbin/resolvconf ] ; then\n";
                    downstream << " dev=$1\n";
                    downstream << " if [ -z $dev ] ; then\n";
                    downstream << "  dev=\"ppp0\"\n";
                    downstream << " fi\n";
                    downstream << " /sbin/resolvconf -d $dev\n";
                    downstream << "else" << "\n";
                    downstream << "cat " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << " > /etc/resolv.conf\n";
                    downstream << "fi" << "\n";
                } else {
                    /* dont update dns */
                }

                if (! pppdHasReplacedefaultrouteSupport && GlobalConfig->currentProfile->getReplaceDefaultRoute()) {
                    downstream << GlobalConfig->pathToIp << " route add  $(cat " << OldDefaultroute << ")" << "\n";
                }

            }
            downfile.close();

            QProcess pppdDownProcess(this);
            QString proc = GlobalConfig->InterpreterShell;
            QStringList args;
            args.append(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".down");
            pppdDownProcess.setEnvironment(*env);
            pppdDownProcess.start(proc, args);
            if (!pppdDownProcess.waitForStarted()) {
                KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , QString("PppdDownScript")));
            } else {
                if (GlobalConfig->KvpncDebugLevel > 1)
                    GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString("PppdDownScript"), QString(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".down")) , KVpncEnum::debug);
                waitForFinished(&pppdDownProcess, 100);

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

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

                if (GlobalConfig->currentProfile->getUseDnsUpdate() && Utils(GlobalConfig).resolvConfAvailable()) {
                    if (GlobalConfig->KvpncDebugLevel > 1)
                        GlobalConfig->appendLogEntry(i18n("resolvconf restored the old /etc/resolv.conf."), KVpncEnum::debug);
                } else {
                    if (GlobalConfig->currentProfile->getUseDnsUpdate())
                        if (GlobalConfig->KvpncDebugLevel > 1)
                            GlobalConfig->appendLogEntry(i18n("/etc/resolv.conf was restored."), KVpncEnum::debug);
                }
            }


            if (GlobalConfig->currentProfile->getAuthMethod() == "chap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2") {
                // remove kvpnc entries from chap-secerets
                QFile ChapSecretsFile("/etc/ppp/chap-secrets");
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1", QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                if (ChapSecretsFile.open(QIODevice::ReadOnly)) {
                    QString chapsecret_content = "";
                    bool kvpnc_start_marker_found = false;
                    bool kvpnc_end_marker_found = false;
                    QStringList contentlist = QString(ChapSecretsFile.readAll()).split("\n");
                    for (int i = 0; i < contentlist.size(); ++i) {
                        QString line = contentlist.at(i);
                        if (line == "# --- generated by kvpnc. Do not edit it.") {
                            kvpnc_end_marker_found = true;
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("End marker in %1 found"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                        }
                        if (line == "# +++ generated by kvpnc. Do not edit it.") {
                            kvpnc_start_marker_found = true;
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("Start marker in %1 found"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                        }

                        if (kvpnc_start_marker_found == false) {
                            chapsecret_content += line;
                            chapsecret_content += '\n';
                        }
                    }
                    ChapSecretsFile.close();
                    if (ChapSecretsFile.remove()) {
                        if (GlobalConfig->KvpncDebugLevel > 2)
                            GlobalConfig->appendLogEntry(i18n("File %1 successfully removed"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                        //        ChapSecretsFile.setName("/etc/ppp/chap-secrets2");
                        if (ChapSecretsFile.open(QIODevice::WriteOnly)) {
                            QTextStream stream(&ChapSecretsFile);
                            stream << chapsecret_content;
                            ChapSecretsFile.close();
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("File %1 successfully rewritten"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                        } else {
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("File %1 rewrite failed"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
                        }
                    } else {
                        if (GlobalConfig->KvpncDebugLevel > 2)
                            GlobalConfig->appendLogEntry(i18n("File %1 remove failed"  , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
                    }

                } else {
                    GlobalConfig->appendLogEntry(i18n("File %1 could not be opened."  , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
                }
            }
            if (GlobalConfig->currentProfile->getAuthMethod() == "pap") {
                // remove kvpnc entries from pap-secerets
                QFile papSecretsFile("/etc/ppp/pap-secrets");
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1", QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                if (papSecretsFile.open(QIODevice::ReadOnly)) {
                    QString papsecret_content = "";
                    bool kvpnc_start_marker_found = false;
                    bool kvpnc_end_marker_found = false;
                    QStringList contentlist = QString(papSecretsFile.readAll()).split("\n");
                    for (int i = 0; i < contentlist.size(); ++i) {
                        QString line = contentlist.at(i);
                        if (line == "# --- generated by kvpnc. Do not edit it.") {
                            kvpnc_end_marker_found = true;
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("End marker in %1 found"  , QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
                        }
                        if (line == "# +++ generated by kvpnc. Do not edit it.") {
                            kvpnc_start_marker_found = true;
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("Start marker in %1 found"  , QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
                        }

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

                } else {
                    GlobalConfig->appendLogEntry(i18n("File %1 could not be opened."  , QString("/etc/ppp/pap-secrets")), KVpncEnum::error);
                }
            }
            setGuiStatus(KVpncEnum::disconnected);
            GlobalConfig->status = KVpncEnum::disconnected;
            connectCounter = 0;
            connectionEnded();
        } else if (ConnectingProcess == VpnAccountData::openvpn) {
            if ( managementhandler )
            {
                managementhandler->greetingtimer->stop();
                managementhandler->closeConnection();
                while ( ! managementhandler->socketReallyClosed )
                {
                    if (GlobalConfig->appPointer->hasPendingEvents())
                        GlobalConfig->appPointer->processEvents();
                    usleep(500);
                }
                delete managementhandler;
            }
            if (OpenvpnProcess != 0 ) {
                disconnect(OpenvpnProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutput_openvpn()));
                //disconnect( OpenvpnProcess, SIGNAL( readyReadStandardError() ), this, SLOT( readOutput_openvpn() ) );
                disconnect(OpenvpnProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(openvpn_exited(int, QProcess::ExitStatus)));
                if (OpenvpnProcess->state() == QProcess::Running) {
                    OpenvpnProcess->kill();
                }
                delete OpenvpnProcess;
                OpenvpnProcess = 0L;

            }
            connectionEnded();

        } else if (ConnectingProcess == VpnAccountData::vtun) {

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

            //     terminateConnection( VtundProcess );
            //     VtundProcess = new QProcess(this);
            //  QString proc =  GlobalConfig->pathToKillall ;
            //      QStringList args;
            //     args.apppend( "vtund" );
            //
            //     connect( VtundProcess, SIGNAL( readyReadStandardOutput() ), this, SLOT( readFromStdout_disconnect() ) );
            //     connect( VtundProcess, SIGNAL( readyReadStandardError() ), this, SLOT( readFromStderr_disconnect() ) );
            //
            //  VtundProcess->setEnvironment(*env);
            //  VtundProcess.start(proc,args);
            //     if ( !VtundProcess->waitForStarted() ) {
            //      KMessageBox::sorry( this, i18n( "Failed to start \"%1\"." , QString( "killall vtund" )) );
            //     }
//         else
//         {
//          sleep(1);
//         }
//         delete VtundProcess;
//         VtundProcess=0L;


            sleep(2);
            delete VtundProcess;
            VtundProcess = 0L;
            disconnect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));
            connectionEnded();

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

            if (SshProcess && SshProcess->state() == QProcess::Running) {
                disconnect(SshProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ssh()));
                disconnect(SshProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ssh()));
                disconnect(SshPty, SIGNAL(readyRead()), this, SLOT(readFromPty_ssh()));
                if (SshProcess != 0) {
                    SshProcess->kill();
                    sleep(1);
                    if (SshProcess->state() == QProcess::Running)
                        SshProcess->kill();
                    sleep(1);
                    if (SshProcess->state() == QProcess::Running)
                        SshProcess->kill();
                    sleep(1);
                    if (SshProcess->state() == QProcess::Running)
                        SshProcess->kill();
                }
            }

            //     terminateConnection( SshProcess );
            //     SshProcess = new QProcess(this);
            //  QString proc =  GlobalConfig->pathToKillall;
            //      QStringList args;
            //     args.append( "openvpn" );
            //
            //     connect( DisconnectProcess, SIGNAL( readAllStandardOutput() ), this, SLOT( readFromStdout_disconnect() ) );
            //     connect( DisconnectProcess, SIGNAL( readAllStandardError() ), this, SLOT( readFromStderr_disconnect() ) );
            //
            //  DisconnectProcess->setEnvironment(*env);
            //  DisconnectProcess->start(proc,args);
            //     if ( !DisconnectProcess->waitForStarted() ) {
            //      KMessageBox::sorry( this, i18n( "Failed to start \"%1\".", QString( "killall ssh" )) );
            //     }
//         else
//             {
//                 sleep(1);
//             }
            disconnect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));
            if (SshProcess != 0L) {
                delete SshProcess;
                SshProcess = 0L;
            }
            connectionEnded();
            //connectionEnded();
            setGuiStatus(KVpncEnum::disconnected);
            ConnectingProcess = -1;
        } else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_plain ) {

            //if (QFile("/var/run/l2tpd.pid").exists()) {
            //	if (GlobalConfig->KvpncDebugLevel > 1)
            //		GlobalConfig->appendLogEntry(i18n("Using control interface for disconnecting l2tp connection"),KVpncEnum::debug);
            //	QFile L2tpdControlFile ( "/var/run/l2tp-control" );
            //	QTextStream stream( &L2tpdControlFile );
            //	if ( L2tpdControlFile.open( IO_WriteOnly  ) ) {
            //		stream << "d " << GlobalConfig->currentProfile->getName() << "\n";
            //		L2tpdControlFile.close();
            //	}
            //}
            //else
            //{
            //	if (QFile("/var/run/l2tpd.pid").exists())
            //	{
            //		if (GlobalConfig->KvpncDebugLevel > 1)
            //			GlobalConfig->appendLogEntry(i18n("Using control interface for disconnecting l2tp connection"),KVpncEnum::debug);
            //		QFile L2tpdControlFile ( "/var/run/l2tp-control" );
            //		QTextStream stream( &L2tpdControlFile );
            //		if ( L2tpdControlFile.open( IO_WriteOnly  ) ) {
            //			stream << "d " << GlobalConfig->currentProfile->getName() << "\n";
            //			L2tpdControlFile.close();
            //		}
            //		else
            //		{
            if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd ) {
                if (L2tpdProcess != 0L && L2tpdProcess->state() == QProcess::Running) {
                    L2tpWaitForPppUpTimer.stop();
                    disconnect(this, SIGNAL(L2tpdStdoutRecieved()), this, SLOT(processStdout_l2tpd()));
                    disconnect(this, SIGNAL(L2tpdStderrRecieved()), this, SLOT(processStderr_l2tpd()));

                    if (L2tpdProcess->state() == QProcess::Running) {
                        L2tpdProcess->kill();
                        if (L2tpdProcess != 0L && L2tpdProcess->state() == QProcess::Running)
                            L2tpdProcess->terminate();
                        sleep(1);
                        if (L2tpdProcess != NULL  && L2tpdProcess->state() == QProcess::Running)
                            L2tpdProcess->kill();
                    }
                }
            }
            if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp ) {
                disconnect(OpenL2tpProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_openl2tp()));
                disconnect(OpenL2tpProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_openl2tp()));

                OpenL2tpProcess->kill();

                delete OpenL2tpProcess;
                OpenL2tpProcess = 0L;

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

            }


            if ( !Utils ( GlobalConfig, parent ).unloadKernelModule ( "slhc", parent ) ) {
                if ( GlobalConfig->KvpncDebugLevel > 3 )
                    GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed", QString("slhc") ), KVpncEnum::debug );
            } else {
                if ( GlobalConfig->KvpncDebugLevel > 3 )
                    GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeeded", QString("slhc") ), KVpncEnum::debug );
            }
            if ( !Utils ( GlobalConfig, parent ).unloadKernelModule ( "ppp_generic", parent ) ) {
                if ( GlobalConfig->KvpncDebugLevel > 3 )
                    GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed.", QString("ppp_generic") ), KVpncEnum::debug );
            } else {
                if ( GlobalConfig->KvpncDebugLevel > 3 )
                    GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeeded", QString("ppp_generic") ), KVpncEnum::debug );
            }
            if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp ) {
                if ( !Utils ( GlobalConfig, parent ).unloadKernelModule ( "pppox", parent ) ) {
                    if ( GlobalConfig->KvpncDebugLevel > 3 )
                        GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed.", QString("pppox") ), KVpncEnum::debug );
                } else {
                    if ( GlobalConfig->KvpncDebugLevel > 3 )
                        GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeeded", QString("pppox") ), KVpncEnum::debug );
                }
                if ( !Utils ( GlobalConfig, parent ).unloadKernelModule ( "pppol2tp", parent ,true ) ) {
                    if ( GlobalConfig->KvpncDebugLevel > 3 )
                        GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" failed", QString("pppol2tp") ), KVpncEnum::debug );
                } else {
                    if ( GlobalConfig->KvpncDebugLevel > 3 )
                        GlobalConfig->appendLogEntry ( i18n ( "Unloading module \"%1\" succeeded", QString("pppol2tp") ), KVpncEnum::debug );
                }
                startStopOpenl2tp ( true );
                sleep ( 2 );
                startStopOpenl2tp();
            }



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

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

                    } else {
                        GlobalConfig->appendLogEntry ( i18n ( "File %1 could not opened!", QString("/etc/ppp/chap-secrets") ), KVpncEnum::error );
                    }
                }
                if ( GlobalConfig->currentProfile->getAuthMethod() == "pap" ) {
                    // remove kvpnc entries from pap-secerets
                    QFile papSecretsFile ( "/etc/ppp/pap-secrets" );
                    if ( GlobalConfig->KvpncDebugLevel > 0 )
                        GlobalConfig->appendLogEntry ( i18n ( "pppd secrets file: %1", QString("/etc/ppp/chap-secrets") ), KVpncEnum::debug );
                    QTextStream stream ( &papSecretsFile );
                    if ( papSecretsFile.open ( IO_ReadOnly ) ) {
                        QString line = "";
                        QString papsecret_content = "";
                        bool kvpnc_start_marker_found = false;
                        bool kvpnc_end_marker_found = false;
                        while ( !stream.atEnd() ) {
                            line = stream.readLine(); // line of text excluding '\n'
                            if ( line == "# --- generated by kvpnc. Do not edit it." ) {
                                kvpnc_end_marker_found = true;
                                if ( GlobalConfig->KvpncDebugLevel > 2 )
                                    GlobalConfig->appendLogEntry ( i18n ( "End marker in %1 found", QString("/etc/ppp/pap-secrets") ), KVpncEnum::debug );
                            }
                            if ( line == "# +++ generated by kvpnc. Do not edit it." ) {
                                kvpnc_start_marker_found = true;
                                if ( GlobalConfig->KvpncDebugLevel > 2 )
                                    GlobalConfig->appendLogEntry ( i18n ( "Start marker in %1 found", QString("/etc/ppp/pap-secrets") ), KVpncEnum::debug );
                            }

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

                    } else {
                        GlobalConfig->appendLogEntry ( i18n ( "File %1 could not opened!", QString("/etc/ppp/pap-secrets") ), KVpncEnum::error );
                    }
                }
                // remove kvpnc entries from /etc/l2tpd/l2tp-secrets
                QFile L2tpSecretsFile ( "/etc/l2tpd/l2tp-secrets" );
                if ( GlobalConfig->KvpncDebugLevel > 0 )
                    GlobalConfig->appendLogEntry ( i18n ( "l2pd secrets file: %1", QString("/etc/l2tpd/l2tp-secrets") ), KVpncEnum::debug );
                QTextStream stream ( &L2tpSecretsFile );
                if ( L2tpSecretsFile.open ( IO_ReadOnly ) ) {
                    QString line = "";
                    QString l2tpsecret_content = "";
                    bool kvpnc_start_marker_found = false;
                    bool kvpnc_end_marker_found = false;
                    while ( !stream.atEnd() ) {
                        line = stream.readLine(); // line of text excluding '\n'
                        if ( line == "# --- generated by kvpnc. Do not edit it." ) {
                            kvpnc_end_marker_found = true;
                            if ( GlobalConfig->KvpncDebugLevel > 2 )
                                GlobalConfig->appendLogEntry ( i18n ( "End marker in %1 found", QString("/etc/l2tpd/l2tp-secrets") ), KVpncEnum::debug );
                        }
                        if ( line == "# +++ generated by kvpnc. Do not edit it." ) {
                            kvpnc_start_marker_found = true;
                            if ( GlobalConfig->KvpncDebugLevel > 2 )
                                GlobalConfig->appendLogEntry ( i18n ( "Start marker in %1 found", QString("/etc/l2tpd/l2tp-secrets") ), KVpncEnum::debug );
                        }

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

                } else {
                    GlobalConfig->appendLogEntry ( i18n ( "File %1 could not opened!", QString("/etc/l2tpd/l2tp-secrets") ), KVpncEnum::error );
                }
            }

            //connectionEnded();
            setGuiStatus(KVpncEnum::disconnected);
            ConnectingProcess = -1;
        }

        else {
            prevConnectionState = KVpncEnum::disconnected;
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Not connected.\n"), KVpncEnum::debug);
            setGuiStatus(KVpncEnum::disconnected);
            ConnectingProcess = -1;
        }
    }
    if (GlobalConfig->KvpncDebugLevel > 0)
        GlobalConfig->appendLogEntry(i18n("Disconnected."), KVpncEnum::debug);
}

void KVpnc::helpClicked()
{

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

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

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

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

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

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


//  appHelpActivated ();


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

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


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

     QStringList list = iface.getAllNetworkInterfaces();
     QString netliststring="";
     for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
      QString aa = QString( *it );
      netliststring+=" ";
      netliststring+=aa;
     }

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

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

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

     QString interfaceip = "Interface IP of eth1:2: " + iface.getInterfaceIP( "eth1:2" );
     if ( interfaceip.isEmpty() )
     interfaceip += "none";
     mw->DebugOutput->append( interfaceip );
    */
//   NetworkInterface iface(GlobalConfig,parent);
//   QString gatewayofdefaultinterface = "GW IP of default interface: " + iface.getGatewayOfDefaultInterface();
//   mw->DebugOutput->append( gatewayofdefaultinterface );
//   QString NetmaskOfInterface = "netmask IP of  interface: " + iface.getNetmaskOfInterface("wlan0");
//   mw->DebugOutput->append( NetmaskOfInterface );
    /*
      if (iface.inSameNetwork("192.168.10.253","255.255.255.0","192.168.10.222","255.255.255.0"))
       mw->DebugOutput->append("192.168.10.253 in same network as 192.168.10.222: yes");
      else
       mw->DebugOutput->append("192.168.10.253 in same network as 192.168.10.222: no");

      if (iface.inSameNetwork("192.168.10.253","255.255.255.0","192.168.1.2","255.255.255.0"))
       mw->DebugOutput->append("192.168.10.253 in same network as 192.168.1.2: yes");
      else
       mw->DebugOutput->append("192.168.10.253 in same network as 192.168.1.2: no");
    */
    /*
      QString gatewayofinterface = "GW IP of interface eth1:1: " + iface.getGatewayOfInterface("eth1:1");
      mw->DebugOutput->append( gatewayofinterface );

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

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

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

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

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

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

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

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

}

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

    pppdCapabilitiesCollected = true;
}

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

    pppdCapabilitiesCollected = true;
}

void KVpnc::donateClicked()
{
    this->slotStatusMsg(i18n("Calling KVpnc website..."), ID_FLASH_MSG);

    QString donateurl = "http://home.gna.org/kvpnc/en/donate.html";
    QDesktopServices::openUrl(QString(donateurl));
    if (GlobalConfig->KvpncDebugLevel > 1)
        GlobalConfig->appendLogEntry(i18n("URL \"%1\" called." , donateurl), KVpncEnum::debug);
}

void KVpnc::visitHomepageClicked()
{
    QString homepageurl = "http://home.gna.org/kvpnc/en/index.html";
    QString browser = QString(KConfigGroup(KGlobal::config(), "General").readEntry("BrowserApplication")).remove(".", Qt::CaseSensitive);

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

    //  KRun * run = new KRun( KUrl( homepageurl ),0,false,true );
    //  if ( run )
    //   ;

    QProcess WebpageProcess(this);
    QString proc;
    QStringList args;
    proc = browser;
    args.append(homepageurl);

    WebpageProcess.startDetached(proc, args);
//     if (WebpageProcess.state() == QProcess::NotRunning) {
//   GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , i18n("visit homepage")), KVpncEnum::error);
//   KMessageBox::error(this, i18n("\"%1\" with %2 start failed." , i18n("visit homepage") , browser));
//     } else {
    if (GlobalConfig->KvpncDebugLevel > 0)
        GlobalConfig->appendLogEntry(i18n("\"%1\" started." , i18n("visit homepage")), KVpncEnum::debug);

    if (GlobalConfig->KvpncDebugLevel > 1)
        GlobalConfig->appendLogEntry(i18n("URL \"%1\" with browser \"%2\" called." , homepageurl , browser), KVpncEnum::debug);
//     }
}

void KVpnc::readOutputFrom_vpnc()
{
    if (GlobalConfig->KvpncDebugLevel > 3)
        GlobalConfig->appendLogEntry("readOutputFrom_vpnc!", KVpncEnum::debug);
    QStringList msg_list = QString(VpncProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        handleOutputFrom_vpnc(msg, OutputMsg::normal);

    }
}

void KVpnc::readFromPty_vpnc()
{
//  if (GlobalConfig->KvpncDebugLevel > 3)
//   GlobalConfig->appendLogEntry( "readFromPty_vpnc!", KVpncEnum::debug );

    QStringList msg_list = QString(VpncPty->readAll()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        if ((sendingVpncConfigInProgress && GlobalConfig->KvpncDebugLevel > 8) || !sendingVpncConfigInProgress)
            handleOutputFrom_vpnc(msg, OutputMsg::pty);
//   else {
//    if (GlobalConfig->KvpncDebugLevel > 5)
//     GlobalConfig->appendLogEntry( "readFromPty_vpnc: %1"+msg, KVpncEnum::debug );
//   }


    }
}

void KVpnc::handleOutputFrom_vpnc(QString msg, OutputMsg::MsgType type)
{
    bool connectSuccess = false;
    bool abort = false;
    bool doContinue = true;
//   mw->DebugOutput->append( "readOutputFrom_vpnc line:\n"+ProcessMsg_connect );
    if (deviceaddrstr2addr) {
        deviceaddrstr = msg;

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

    if (type == OutputMsg::normal) {
        if (GlobalConfig->KvpncDebugLevel > 3) {
            GlobalConfig->appendLogEntry("[vpnc] " + msg, KVpncEnum::debug);
        }
    } else if (type == OutputMsg::error)
        GlobalConfig->appendLogEntry("[vpnc err] " + msg, KVpncEnum::debug);
    else if (type == OutputMsg::pty) {
        if (GlobalConfig->KvpncDebugLevel > 3) {
            GlobalConfig->appendLogEntry("[vpnc pty] " + msg, KVpncEnum::debug);
        }
    }

// 	// vpnc has started, now we can send the config  (only if debug > 0)
// 	if (msg.indexOf("vpnc version", 0, Qt::CaseInsensitive) > -1) {
// 		bool doWrite = true;
// 		if (doWrite) {
// 			// we send config via stdin
//
// 			if (GlobalConfig->KvpncDebugLevel > 2)
// 				GlobalConfig->appendLogEntry(i18n("Sending config to \"%1\"..." , QString("vpnc")), KVpncEnum::debug);
//
// 			sendingVpncConfigInProgress = true;
// 			VpncPty->write(vpncConfig.toUtf8());
// 			sendingVpncConfigInProgress = false;
//
// 			if (GlobalConfig->KvpncDebugLevel > 2)
// 				GlobalConfig->appendLogEntry(i18n("Config to \"%1\" sent." , QString("vpnc")), KVpncEnum::debug);
//
// 		}
// 	}

    if (msg.indexOf("Enter IPSec secret for", 0, Qt::CaseInsensitive) > -1) {
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("[vpnc] " + i18n("Group password requested, send it...\n"), KVpncEnum::debug);

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

        if (GlobalConfig->KvpncDebugLevel > 4)
            GlobalConfig->appendLogEntry("[vpnc] " + i18n("Group password: %1\n", GrpPassStr), KVpncEnum::debug);

        VpncPty->write(GrpPassStr.toUtf8());
        VpncPty->write("\n");

    }

    // requesting password
    else if (msg.indexOf("password for", 0, Qt::CaseInsensitive) > -1) {
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("[vpnc] " + i18n("User password requested, send it...\n"), KVpncEnum::debug);

        QString UserPassStr = GlobalConfig->TmpPassword;

        if (GlobalConfig->KvpncDebugLevel > 4)
            GlobalConfig->appendLogEntry("[vpnc] " + i18n("User password: %1\n", UserPassStr), KVpncEnum::debug);

        VpncPty->write(UserPassStr.toUtf8());
        VpncPty->write("\n");

    }


    //"Enter Username and Password"

    // requesting gatway
    else if (msg.indexOf("Enter IPSec gateway address", 0, Qt::CaseInsensitive) > -1) {
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("[vpnc] " + i18n("IPSec gateway address requested, send it...\n"), KVpncEnum::debug);
        //QString GatewayStr = GlobalConfig->currentProfile->getGateway();
        QString GatewayStr = GlobalConfig->TmpGatewayIP;
        VpncPty->write(GatewayStr.toUtf8());
        VpncPty->write("\n");
    }

    // requesting IPSec ID
    //Enter IPSec ID for
    else if (msg.indexOf("Enter IPSec ID", 0, Qt::CaseInsensitive) > -1 || msg.indexOf("Enter IPSec ID for", 0, Qt::CaseInsensitive) > -1) {
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("[vpnc] " + i18n("IPSec ID requested, send it...\n"), KVpncEnum::debug);
        QString IpsecIDStr = GlobalConfig->currentProfile->getID();
        VpncPty->write(IpsecIDStr.toUtf8());
        VpncPty->write("\n");
    }

    // requesting username
    else if ((msg.indexOf("Enter username for", 0, Qt::CaseInsensitive) > -1) && !msg.indexOf("Enter Username and Password", 0, Qt::CaseInsensitive) > -1) {
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("[vpnc] " + i18n("Username requested, send it...\n"), KVpncEnum::debug);

        QString UsernameStr;
        UsernameStr = GlobalConfig->TmpUsername;

        VpncPty->write(UsernameStr.toUtf8());
        VpncPty->write("\n");
    }

    // using interface tun0
    else if (msg.indexOf("using interface", 0, Qt::CaseInsensitive) > -1) {
        VpncDevice = ProcessMsg_connect.section(' ', 2, 2);    // using interface tun0 -> tun0
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("Tunnel device: %1\n" , VpncDevice), KVpncEnum::debug);
    }

    //got address 194.95.192.28
    else if (msg.indexOf("got address", 0, Qt::CaseInsensitive) > -1) {
        // "got address 194.95.192.28" => "194.95.192.28"
//    TunnelInterfaceIP = ProcessMsg_connect.section ( '\n', 1, 1 );
//    TunnelInterfaceIP = TunnelInterfaceIP.right ( TunnelInterfaceIP.length() - 12 );
        TunnelInterfaceIP = ProcessMsg_connect.section(' ', 2, 2);

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


    else if (msg.indexOf("started in background", 0, Qt::CaseInsensitive) > -1)
        connectSuccess = true;

    else if (msg.indexOf("started in foreground", 0, Qt::CaseInsensitive) > -1)
        connectSuccess = true;

    else if (msg.indexOf("tun0", 0, Qt::CaseInsensitive) > -1)
        GlobalConfig->appendLogEntry(i18n("line: %1\n" , msg), KVpncEnum::debug);

    else if (msg.indexOf("AUTHENTICATION_FAILED", 0, Qt::CaseInsensitive) > -1) {
        timer.stop();
        connectCounter = 0;
        disconnect(&timer, SIGNAL(timeout()), this, SLOT(slotConnectTimedOut()));
        KMessageBox::error(this, i18n("Authentication failed (%1)." , i18n("group password")));
        GlobalConfig->appendLogEntry(i18n("Authentication failed (%1)." , i18n("group password")) , KVpncEnum::error);
        //abort = true;
        AuthRetry = true;
        GlobalConfig->haveUserData = false;
        connectClicked();
    }

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

    else if (msg.indexOf("authentication unsuccessful", 0, Qt::CaseInsensitive) > -1) {
        timer.stop();
        connectCounter = 0;
        disconnect(&timer, SIGNAL(timeout()), this, SLOT(slotConnectTimedOut()));
        KMessageBox::error(this, i18n("Authentication failed (%1)." , i18n("user password")));
        GlobalConfig->appendLogEntry(i18n("Authentication failed (%1)." , i18n("user password")) , KVpncEnum::error);
        //abort = true;
        AuthRetry = true;
        GlobalConfig->haveUserData = false;
        disconnect(VpncProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutputFrom_vpnc()));
        timer.stop();
        connectClicked();
    }

    // no ip for gateway
    else if (msg.indexOf("vpnc: unknown host `<Replace with your gateway IP address>' ", 0, Qt::CaseInsensitive) > -1) {
        timer.stop();
        connectCounter = 0;
        disconnect(&timer, SIGNAL(timeout()), this, SLOT(slotConnectTimedOut()));
        KMessageBox::error(this, i18n("You have to enter an IP address for the remote gateway."));
        GlobalConfig->appendLogEntry(i18n("You have to enter an IP address for the remote gateway.") , KVpncEnum::error);
        abort = true;
    }

    // no answer
    else if (msg.indexOf("no response from target", 0, Qt::CaseInsensitive) > -1) {
        timer.stop();
        connectCounter = 0;
        disconnect(&timer, SIGNAL(timeout()), this, SLOT(slotConnectTimedOut()));
        KMessageBox::error(this, i18n("No response from VPN server"));
        GlobalConfig->appendLogEntry(i18n("No response from VPN server") , KVpncEnum::error);
        abort = true;
    }

    // initalizing tunnel interface failed
    else if (msg.indexOf("can't initialise tunnel interface", 0, Qt::CaseInsensitive) > -1) {
        timer.stop();
        connectCounter = 0;
        disconnect(&timer, SIGNAL(timeout()), this, SLOT(slotConnectTimedOut()));
        KMessageBox::error(this, i18n("Tunnel interface cannot be initialized."));
        GlobalConfig->appendLogEntry(i18n("Tunnel interface cannot be initialized.") , KVpncEnum::error);
        abort = true;
        doContinue = false;
    }

    // /dev/net/tun does not exist
    else if (msg.indexOf("can't open /dev/net/tun", 0, Qt::CaseInsensitive) > -1) {
        if (doContinue) {
            KMessageBox::error(this, i18n("Device file \"%1\" cannot be opened." , QString("/dev/net/tun")));
            GlobalConfig->appendLogEntry(i18n("Device file \"%1\" cannot be opened." , QString("/dev/net/tun")) , KVpncEnum::error);
            abort = true;
        }
    }

    // host unknown
    else if (msg.indexOf("unknown host" , 0, Qt::CaseInsensitive) > -1) {
        timer.stop();
        connectCounter = 0;
        disconnect(&timer, SIGNAL(timeout()), this, SLOT(slotConnectTimedOut()));
        KMessageBox::error(this, i18n("Host unknown"));
        GlobalConfig->appendLogEntry(i18n("Host unknown") , KVpncEnum::error);
        abort = true;
    }

    //socket creation failed
    else if (msg.indexOf("making socket", 0, Qt::CaseInsensitive) > -1) {
        timer.stop();
        connectCounter = 0;
        disconnect(&timer, SIGNAL(timeout()), this, SLOT(slotConnectTimedOut()));
        KMessageBox::error(this, i18n("Socket creation failed"));
        GlobalConfig->appendLogEntry(i18n("Socket creation failed") , KVpncEnum::error);
        abort = true;
    }

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

    // binding to port failed
    else if (msg.indexOf("binding to port", 0, Qt::CaseInsensitive) > -1 || msg.indexOf("Address already in use", 0, Qt::CaseInsensitive) > -1) {
        timer.stop();
        connectCounter = 0;
        disconnect(&timer, SIGNAL(timeout()), this, SLOT(slotConnectTimedOut()));
        //   if ( GlobalConfig->KvpncDebugLevel > 0 )
        //    GlobalConfig->appendLogEntry( i18n( "Binding to port failed. Another vpnc is running, terminate it and try reconnect ." ), KVpncEnum::debug );
        GlobalConfig->appendLogEntry(QString("binding" + ProcessMsg_connect), KVpncEnum::debug);
        //   QFile oldpidfile( tmpPath + "vpnc-pid." + GlobalConfig->currentProfile->getName() + ".pid" );
        //   if (oldpidfile.exists())
        //   {
        //    if ( GlobalConfig->KvpncDebugLevel > 0 )
        //     GlobalConfig->appendLogEntry( i18n( "Old pid file found: %1" ,oldpidfile.name()), KVpncEnum::debug );
        //    QTextStream pidFileStream( &oldpidfile );
        //    QString Vpnc_pid = "";
        //    if ( oldpidfile.open( QIODevice::ReadOnly ) )
        //    {
        //     Vpnc_pid = pidFileStream.readLine();
        //     oldpidfile.close();
        //    }
        //    QProcess killvpncprocess(this);
        //    if ( !Vpnc_pid.isEmpty() )
        //    {
        //
        //     if ( GlobalConfig->KvpncDebugLevel > 0 )
        //      GlobalConfig->appendLogEntry( i18n( "Vpnc pid file contains a pid: %1, try to terminate the process with this pid." , Vpnc_pid ) , KVpncEnum::debug);
        //     QString proc = GlobalConfig->pathToKill;
        //     QStringList args;
        //     args.append("-3");
        //     args.append(Vpnc_pid);
        //    }
        //    else
        //    {
        //     if ( GlobalConfig->KvpncDebugLevel > 0 )
        //      GlobalConfig->appendLogEntry( i18n( "No vpnc pid file found, using \"killall\" for killing vpnc." ), KVpncEnum::debug );
        //     args.append("-3");
        //
        //    }
        //
        //    args.append("vpnc");
        //    killvpncprocess.setEnvironment(*env);
        //    killvpncprocess.start(proc,args);
        //    if (!killvpncprocess.waitForStarted())
        //     GlobalConfig->appendLogEntry( i18n( "%1 could not be killed." ,"vpnc") ,KVpncEnum::error);
        //
        //    killvpncprocess.waitForFinished();
        //   }
        //   else
        //   {
        //    //kill vpnc
        //    QProcess killvpncprocess(this);
        //    QString proc = GlobalConfig->pathToKillall;
        //    QStringList args;
        //    args.append("vpnc");
        //    killvpncprocess.setEnvironment(*env);
        //    killvpncprocess.start(proc,args);
        //    if (!killvpncprocess.waitForStarted())
        //     GlobalConfig->appendLogEntry( i18n( "%1 could not be killed." ,"vpnc") ,KVpncEnum::error);
        //
        //    killvpncprocess.waitForFinished();

        //    disconnectClicked();
        //    connectClicked();
        //   }
        //
        //   VpncDisconnectScript = tmpPath + "vpnc-disconnect." + GlobalConfig->currentProfile->getID() + ".sh";
        //
        //   QString OldDefaultroute="";
        //   QString oldProfileName="";
        //
        //   QDir tmpDir(tmpPath);
        //
        //   QStringList lst = tmpDir.entryList( "default-route.*" );
        //   if (!lst.isEmpty())
        //   {
        //    OldDefaultroute = lst.first(); // default-route.<id>
        //
        //    if ( GlobalConfig->KvpncDebugLevel > 0 )
        //     GlobalConfig->appendLogEntry( i18n( "Old defaultroute file found: %1" ,OldDefaultroute), KVpncEnum::debug );
        //
        //
        //    QFile file( VpncDisconnectScript );
        //    QTextStream stream( &file );
        //    if ( file.open( QIODevice::WriteOnly ) )
        //    {
        //     //     stream <<  "#!"<< GlobalConfig->InterpreterShell << "\n";
        //     stream << "# generated by kvpnc. Do not edit it." << "\n";
        //     stream << "\n";
        //     if (GlobalConfig->currentProfile->getReplaceDefaultRoute())
        //     {
        //      stream << GlobalConfig->pathToIp+" route del default > /dev/null 2>&1\n";
        //      stream << GlobalConfig->pathToIp+" route add $(cat \"" + OldDefaultroute + "\")\n";
        //     }
        //     //stream << GlobalConfig->pathToIp+" route del $(cat \"" + VpncGateway + "\")\n";
        //  /* update dns? */
        //     if (GlobalConfig->currentProfile->getUseDnsUpdate())
        //     {
        //     stream << "chmod u+w  /etc/resolv.conf\n";
        //     stream << "if [ -f /sbin/resolvconf ] ; then\n";
        //     stream << "sbin/resolvconf -d "+GlobalConfig->DnsDevice+"\n";
        //     oldProfileName=OldDefaultroute.section('/',-2,-1); // /root/.kde/share/apps/kvpnc/default-route.<name> -> <name>
        //     if (!oldProfileName.isEmpty() &&QFile("/etc/resolv.conf.before.kvpnc_"+oldProfileName).exists() )
        //     {
        //      if ( GlobalConfig->KvpncDebugLevel > 0 )
        //       GlobalConfig->appendLogEntry( i18n( "Old resolv.conf file found, restore it." ), KVpncEnum::debug );
        //
        //      stream << "else\n";
        //      stream << " mv /etc/resolv.conf.before.kvpnc_"+oldProfileName+" /etc/resolv.conf\n";
        //     }
        //     stream << "fi\n";
        //    }
        //    else {
        //     /* dont update dns */
        //}
        //
        //     stream << GlobalConfig->pathToIp+" route flush cache\n";
        //    }
        //    file.close();
        //
        //    DisconnectProcess = new QProcess(this);
        //  QString proc =  GlobalConfig->InterpreterShell ;
        // QStringList args;
        //    args.append( VpncDisconnectScript );
        //
        //    connect( DisconnectProcess, SIGNAL( readAllStandardOutput() ), this, SLOT( readFromStdout_disconnect() ) );
        //    connect( DisconnectProcess, SIGNAL( readyReadStandardError() ), this, SLOT( readFromStderr_disconnect() ) );
        //
        // DisconnectProcess->setEnvironment(*env);
        // DisconnectProcess->start(proc,arg);
        //    if ( !DisconnectProcess->waitForStarted() )
        //    {
        //     KMessageBox::sorry( this, i18n( "Failed to start \"%1\"." , "vpnc_disconnect" ) );
        //    }
        //    else
        //    {
        //     if ( GlobalConfig->KvpncDebugLevel > 0 )
        //      GlobalConfig->appendLogEntry( i18n( "Disconnect script started." ), KVpncEnum::debug );
        //    }
        //    setGuiStatus(KVpncEnum::disconnected);
        //    connectionEnded();
        //   }
        //
        //   if ( GlobalConfig->KvpncDebugLevel > 0 )
        //    GlobalConfig->appendLogEntry( i18n( "Trying reconnect..." ), KVpncEnum::debug );
        //
        //   connectClicked();

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

    // binding to port 500: Address already in use
    //  else if ( msg.indexOf( "Address already in use", 0, Qt::CaseInsensitive ) > -1 )
    //  {

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

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


    //    if ( GlobalConfig->KvpncDebugLevel > 0 )
    //     GlobalConfig->appendLogEntry( i18n( "Binding to port failed. Another program is running at this port, terminate it and try reconnect ." ), KVpncEnum::debug );
    /*
       QFile oldpidfile( tmpPath + "vpnc-pid." + GlobalConfig->currentProfile->getName() + ".pid" );
       if (oldpidfile.exists())
       {
        if ( GlobalConfig->KvpncDebugLevel > 0 )
         GlobalConfig->appendLogEntry( i18n( "Old pid file found: %1" ,oldpidfile.name()), KVpncEnum::debug );
        QTextStream pidFileStream( &oldpidfile );
        QString Vpnc_pid = "";
        if ( oldpidfile.open( QIODevice::ReadOnly ) )
        {
         Vpnc_pid = pidFileStream.readLine();
         oldpidfile.close();
        }
        QProcess killvpncprocess(this);
        if ( !Vpnc_pid.isEmpty() )
        {

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

        }

    args.append("vpnc");
    killvpncprocess.setEnvironment(*env);
    killvpncprocess.start(proc,args);
        if (!killvpncprocess.waitForStarted())
         GlobalConfig->appendLogEntry( i18n( "%1 could not be killed." ,"vpnc") ,KVpncEnum::error);

        killvpncprocess.waitForFinished();

       }
       else
       {
        //kill vpnc
        QProcess killvpncprocess(this);
        QString proc = GlobalConfig->pathToKillall;
    QStringList args;
    args.append("vpnc");
    killvpncprocess.setEnvironment(*env);
    killvpncprocess.start(proc, args);
        if (!killvpncprocess.waitForStarted())
         GlobalConfig->appendLogEntry( i18n( "%1 could not be killed." ,"vpnc") ,KVpncEnum::error);

        killvpncprocess.waitForFinished();


    //     disconnectClicked();
    //connectClicked();
    //    }
    */

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


    else if (msg.indexOf("Network is unreachable", 0, Qt::CaseInsensitive) > -1) {
        timer.stop();
        connectCounter = 0;
        disconnect(&timer, SIGNAL(timeout()), this, SLOT(slotConnectTimedOut()));
        KMessageBox::error(this, i18n("No network reachable"));
        GlobalConfig->appendLogEntry(i18n("No network reachable") , KVpncEnum::error);
        //terminateConnection(VpncProcess);
        disconnectClicked();
    }


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

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

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

            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry("[vpnc] " + i18n("Send passcode for Xauth interactive...\n"), KVpncEnum::debug);
            VpncPty->write(GlobalConfig->TmpXauthInterPasscode.toUtf8());
            VpncPty->write("\n");
        }
        //}
    }

    else if (msg.indexOf("Connect Banner", 0 , Qt::CaseInsensitive) > -1) {
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("[vpnc] " + i18n("Connect banner received"), KVpncEnum::debug);
        GlobalConfig->appendLogEntry(ProcessMsg_connect , KVpncEnum::info);
    }


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

        sec = hour = min = 0;

        GlobalConfig->status = KVpncEnum::connected;
        timer.stop();
        connectCounter = 0;
        disconnect(&timer, SIGNAL(timeout()), this, SLOT(slotConnectTimedOut()));

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

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

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

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

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

    if (abort) {
        timer.stop();
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("There is a reason to stop connecting, terminating \"%1\" process." , QString("vpnc")) , KVpncEnum::debug);
        //terminateConnection(VpncProcess);
        disconnectClicked();
        return ;
    }
}

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

    //mw->DebugOutput->append( "readOutputFrom_ciscovpnc!\n" );
    QStringList msg_list = QString(CiscoVpncProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

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


        if (msg.indexOf("illegal read", 0, Qt::CaseInsensitive) > -1) { }

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

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

        // binding to port failed
        if (msg.indexOf("bind: Address already in use", 0, Qt::CaseInsensitive) > -1) {
            //   if ( GlobalConfig->KvpncDebugLevel > 0 )
            //    GlobalConfig->appendLogEntry( i18n( "Binding to port failed. Another vpnc is running, terminate it and try reconnect ." ), KVpncEnum::debug );
            GlobalConfig->appendLogEntry(QString("binding" + msg), KVpncEnum::debug);

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

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

        if (msg.indexOf("The VPN sub-system is busy or has failed.", 0, Qt::CaseInsensitive) > -1) {
            abort = true;
        }

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

        if (msg.indexOf("Reason: A connection is already in the process of being established.", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("There is already an instance of %1 running." , QString("vpnclient")));
            GlobalConfig->appendLogEntry(i18n("There is already an instance of %1 running." , QString("vpnclient")) , KVpncEnum::error);
            abort = true;
        }

        // requesting username
        if (msg.indexOf("Username [", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry("[vpnclient] " + i18n("Username requested, send it...\n"), KVpncEnum::debug);

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

            CiscoVpncProcess->write(UsernameStr.toUtf8());
            CiscoVpncProcess->write("\n");
        }

        // requesting password
        if (msg.indexOf("Password [", 0, Qt::CaseInsensitive) > -1) {

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

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

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


            CiscoVpncProcess->write(UserPassStr.toUtf8());
            CiscoVpncProcess->write("\n");
        }
        if (msg.indexOf("Authenticating user.", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->AuthRetryCount > 1) {
                timer.stop();
                connectCounter = 0;
                disconnect(&timer, SIGNAL(timeout()), this, SLOT(slotConnectTimedOut()));
                KMessageBox::error(this, i18n("Authentication failed (%1)." , i18n("group password")));
                GlobalConfig->appendLogEntry(i18n("Authentication failed (%1)." , i18n("group password")) , KVpncEnum::error);
                //abort = true;
                AuthRetry = true;
                GlobalConfig->haveUserData = false;
                connectClicked();
            } else {
                // nothing here, its first normal try
                GlobalConfig->AuthRetryCount++;
            }
        }
        if (msg.indexOf("Save Password (Y/N)", 0, Qt::CaseInsensitive) > -1) {
            CiscoVpncProcess->write("Y");
            CiscoVpncProcess->write("\n");
        }

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

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

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

                    pass = dlg.main->PasswordEdit->text();

                    bool allowEmptyCertPassword = true; //FIXME: made an option in gui
                    if (!pass.isEmpty() || allowEmptyCertPassword) {

                        if (GlobalConfig->KvpncDebugLevel > 2)
                            GlobalConfig->appendLogEntry("[vpnclient] " + i18n("certificate password got from user"), KVpncEnum::debug);

                        if (GlobalConfig->KvpncDebugLevel > 6)
                            GlobalConfig->appendLogEntry(i18n("Send certificate password: %1" , pass), KVpncEnum::debug);

                        if (dlg.main->SavePasswordCheckBox->isChecked()) {
                            GlobalConfig->currentProfile->setSavePrivateKeyPassword(true);
                            GlobalConfig->currentProfile->setPrivateKeyPass(QString(pass));
                        }

                        GlobalConfig->TmpPrivateKeyPass = QString(pass);

                        //             if ( GlobalConfig->KvpncDebugLevel > 5 )
                        //     GlobalConfig->appendLogEntry( "[vpnclient]: private key password: " + GlobalConfig->TmpPrivateKeyPass, KVpncEnum::debug );

                        if (GlobalConfig->KvpncDebugLevel > 2)
                            GlobalConfig->appendLogEntry("[vpnclient] " + i18n("Send certificate password..."), KVpncEnum::debug);

                        CiscoVpncProcess->write(GlobalConfig->TmpPrivateKeyPass.toUtf8());
                        CiscoVpncProcess->write("\n");
                    } else {
                        GlobalConfig->appendLogEntry("[vpnclient] certificate password empty, stop.", KVpncEnum::error);
                        return;
                    }
                } else {
                    GlobalConfig->appendLogEntry(i18n("Connect canceled because password enter dialog aborted."), KVpncEnum::info);
                    disconnectClicked();
                }
            } else {
                if (CiscoVpncProcess != 0 && CiscoVpncProcess->state() == KProcess::Running) {

                    if (GlobalConfig->KvpncDebugLevel > 6)
                        GlobalConfig->appendLogEntry(i18n("Send certificate password: %1" , PrivKeyPassStr), KVpncEnum::debug);

                    CiscoVpncProcess->write(PrivKeyPassStr.toUtf8());
                    CiscoVpncProcess->write("\n");
                }
                return ;
            }
        }

        if (msg.indexOf("Reason: User authentication failed.", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Authentication failed (%1)." , i18n("user password")));
            GlobalConfig->appendLogEntry(i18n("Authentication failed (%1)." , i18n("user password")) , KVpncEnum::error);
            //abort = true;
            AuthRetry = true;
            GlobalConfig->haveUserData = false;
            disconnect(CiscoVpncProcess, SIGNAL(readyReadStdout()), this, SLOT(readOutputFrom_ciscovpnc()));
            timer.stop();
            connectClicked();
        }

        if (msg.indexOf("Your VPN connection is secure.", 0, Qt::CaseInsensitive) > -1)
            connectSuccess = true;

        if (msg.indexOf("Client address: ", 0, Qt::CaseInsensitive) > -1) {
//    NetworkInterface iface ( GlobalConfig, parent );
//    TunnelInterfaceIP = iface.getInterfaceIP ( CiscoVpncDevice );

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


        }

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

        if (msg.indexOf("Local LAN Access is enabled", 0, Qt::CaseInsensitive) > -1) {
//    GlobalConfig->appendLogEntry ( i18n ( "Local LAN access is enabled." , PrivKeyPassStr ), KVpncEnum::info );
        }

        if (msg.indexOf("Encryption:", 0, Qt::CaseInsensitive) > -1) {
            QString Encryption = ProcessMsg_connect.section(':', 1, 1).trimmed();
            if (GlobalConfig->KvpncDebugLevel > 2)
                GlobalConfig->appendLogEntry(i18n("Encryption algorithm used: %1", Encryption), KVpncEnum::debug);
        }

        if (msg.indexOf("Authentication:", 0, Qt::CaseInsensitive) > -1) {
            QString Authentication = ProcessMsg_connect.section(':', 1, 1).trimmed();
            if (GlobalConfig->KvpncDebugLevel > 2)
                GlobalConfig->appendLogEntry(i18n("Authentication algorithm used: %1", Authentication), KVpncEnum::debug);
        }


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

            sec = hour = min = 0;

            GlobalConfig->status = KVpncEnum::connected;
            timer.stop();
            connectCounter = 0;
            disconnect(&timer, SIGNAL(timeout()), this, SLOT(slotConnectTimedOut()));

            connect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));
            durationTimer.start(1000);
            setGuiStatus(KVpncEnum::connected);
            connectSuccess = false;
            GlobalConfig->AuthRetryCount = 0;

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

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

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

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


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



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

        Disconnecting the VPN connection.

        */
    }
}

void KVpnc::readFromStdout_racoon()
{
    bool abort = false;
    QStringList msg_list = QString(RacoonProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

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

        //  if ( pingtest ) {
        //   //   if ( GlobalConfig->KvpncDebugLevel > 0 )
        //   //    mw->DebugOutput->append( "raw out (pingtest): " + msg );
        //
        //   if ( msg.indexOf( QString("time="), 0, Qt::CaseInsensitive ) > -1 ) {
        //    GlobalConfig->appendLogEntry( "[ping] " + msg, KVpncEnum::success );
        //   } else if ( msg.indexOf( QString("100 % packet loss"), 0, Qt::CaseInsensitive ) > -1 ) {
        //    GlobalConfig->appendLogEntry( "[ping err] " + msg, KVpncEnum::error );
        //   } else {
        //    if ( msg.indexOf( QString("failed to bind"), 0, Qt::CaseInsensitive ) > -1 ) {
        //     KMessageBox::error( this, i18n( "Binding interface failed." ) );
        //     GlobalConfig->appendLogEntry( i18n( "Binding interface failed." ) , KVpncEnum::error );
        //    }
        //    if ( msg.indexOf( QString("Destination Host Unreachable"), 0, Qt::CaseInsensitive ) > -1 ) {
        //     KMessageBox::error( this, i18n( "Destination host is unreachable." ) );
        //     GlobalConfig->appendLogEntry( i18n( "Destination host is unreachable." ) , KVpncEnum::error );
        //    }
        //
        //if (GlobalConfig->KvpncDebugLevel > 0)
        //    GlobalConfig->appendLogEntry( "[ping] " + msg, KVpncEnum::debug );
        //   }
        //  }
        //
        //  // normal
        //  else {



//   if (msg.indexOf ( "ERROR: ", 0, Qt::CaseInsensitive ) > -1 && msg.indexOf ( "algorithm mismatched", 0, Qt::CaseInsensitive ) > -1 )
//   {
//   KMessageBox::error( this, i18n( "Algorithm mismatched, please select another one." ) );
//   GlobalConfig->appendLogEntry ( i18n ( "[racoon err]: algorithm mismatched, please select another one." ) , KVpncEnum::error );
//   abort = true;
//   }

        if (msg.indexOf("ISAKMP-SA established", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon) {
                GlobalConfig->appendLogEntry("[racoon] " + i18n("IPSec phase 1 established."), KVpncEnum::info);
            } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon) {
                GlobalConfig->appendLogEntry("[racoon] " + i18n("Low level IPsec phase 1 established."), KVpncEnum::info);
            }
            racoon_tunnel_state = 1;
            if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon && GlobalConfig->currentProfile->getUseLeftSourceIp()) {
                if ( GlobalConfig->KvpncDebugLevel > 3 )
                    GlobalConfig->appendLogEntry ( i18n ( "Adding virtual IP address" ), KVpncEnum::debug );
                doAddRemoveVirtualIp("add");
            }
            doPingKickupTunnel();
        } else if (msg.indexOf("IPsec-SA established", 0, Qt::CaseInsensitive) > -1) {
            racoon_tunnel_state++;
            if ( racoon_tunnel_state== 2 )
            {

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

                doIptablesRacoon();
                addRouteRacoon();

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

                    sec = hour = min = 0;

                    GlobalConfig->status = KVpncEnum::connected;

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

                    doIptablesRacoon();
                    addRouteRacoon();

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

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

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

            }

        } else if (msg.indexOf("STATE: phase1 down", 0 , Qt::CaseInsensitive ) > -1 ) {
            //KMessageBox::error ( this, i18n ( "Phase1 expired, shutting down tunnel..." ) );
            GlobalConfig->appendLogEntry ( i18n ( "Phase1 expired, shutting down tunnel..." ) , KVpncEnum::info );
            abort = true;
        }

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

        // binding to port failed
        if (msg.indexOf("ERROR: failed to bind to address", 0, Qt::CaseInsensitive) > -1  ||   msg.indexOf("ERROR: no address could be bound.", 0, Qt::CaseInsensitive) > -1) {

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

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

                if (Name == "racoon") {

                    //RacoonProcess->setProcessChannelMode ( QProcess::MergedChannels);
                    //disconnect ( RacoonProcess, SIGNAL ( readyReadStandardOutput() ), this, SLOT ( readFromStdout_racoon() ) );
                    //disconnect ( RacoonProcess, SIGNAL ( readyReadStandardError() ), this, SLOT ( readFromStderr_racoon() ) );

                    if (GlobalConfig->doKillRacoonIfStillRunning && abort == false) {
                        if (GlobalConfig->KvpncDebugLevel > 3)
                            GlobalConfig->appendLogEntry(i18n("%1 could not bind to port, trying to kill it...." , QString("racoon")) , KVpncEnum::error);

                        QProcess killracoonprocess(this);
                        QString proc = GlobalConfig->pathToKillall;
                        QStringList args;
                        args.append("racoon");
                        killracoonprocess.setEnvironment(*env);
                        killracoonprocess.start(proc, args);
                        if (!killracoonprocess.waitForStarted()) {
                            GlobalConfig->appendLogEntry(i18n("%1 could not be killed." , QString("racoon")) , KVpncEnum::error);
                            GlobalConfig->appendLogEntry(QString("[racoon err] " + i18n("Bind to given port has failed. Another %1 process is running. Please stop %1 first." , QString("racoon"))) , KVpncEnum::error);
                            abort = true;
                        } else {
                            waitForFinished(&killracoonprocess, 100);
                            sleep(2);

                            // restart racoon
                            //       if ( RacoonProcess != 0)
                            //               {
                            //        //        RacoonProcess->kill();
                            //                delete RacoonProcess;
                            //                RacoonProcess=0L;
                            //               }

                            putenv((char*)("LC_ALL=C"));
                            RacoonProcess = new QProcess(this);
                            QString proc = GlobalConfig->pathToRacoon;
                            QStringList args;
                            args.append("-F");    // foreground we want :)
                            //args.append( "-v" );
                            args.append("-f");
                            args.append(tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".conf");
                            //args.append ( "-l" ); // logfile (we get content with tail process)
                            //args.append ( tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log" );
                            if (GlobalConfig->KvpncDebugLevel > 0)
                                GlobalConfig->appendLogEntry("racoon: " + GlobalConfig->pathToRacoon + " -f " + tmpPath + "/racoon" + GlobalConfig->currentProfile->getName() + ".conf", KVpncEnum::debug);


                            //RacoonProcess->setProcessChannelMode(QProcess::MergedChannels);
                            //connect ( RacoonProcess, SIGNAL ( readyReadStandardOutput() ), this, SLOT ( readFromStdout_racoon() ) );
                            //connect ( RacoonProcess, SIGNAL ( readyReadStandardError() ), this, SLOT ( readFromStderr_racoon() ) );

                            RacoonProcess->setEnvironment(*env);
                            RacoonProcess->start(proc, args);
                            if (!RacoonProcess->waitForStarted()) {
                                if (GlobalConfig->KvpncDebugLevel > 0)
                                    GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("racoon")) , KVpncEnum::error);

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

        } else if (msg.indexOf("ERROR: fatal BAD-PROPOSAL-SYNTAX", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Bad proposal from peer reported."));
            GlobalConfig->appendLogEntry(i18n("Bad proposal from peer reported, aborting.") , KVpncEnum::error);

            abort = true;
        } else if (msg.indexOf("ERROR: fatal BAD-PROPOSAL-SYNTAX", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Bad proposal from peer reported."));
            GlobalConfig->appendLogEntry(i18n("Bad proposal from peer reported, aborting.") , KVpncEnum::error);

            abort = true;
        } else if (msg.indexOf("ERROR: couldn't find the pskey for", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("The pre shared key could not be found, check PSK settings."));
            GlobalConfig->appendLogEntry(i18n("PSK is missing, aborting.") , KVpncEnum::error);

            abort = true;
        } else if (msg.indexOf("ERROR: failed to process packet.", 0, Qt::CaseInsensitive) > -1) {
            //   KMessageBox::error( this, i18n( "failed to process packet" ) );
            GlobalConfig->appendLogEntry(i18n("failed to process packet") , KVpncEnum::error);

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

            abort = true;
        } else if (msg.indexOf("ERROR: delete phase1 handle.", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Phase 1 negotiation of IPSec connection has failed. Please check encryption of phase 1 and hash algorithm."));
            GlobalConfig->appendLogEntry(i18n("Phase 1 negotiation of IPSec connection has failed. Please check encryption of phase 1 and hash algorithm.") , KVpncEnum::error);

            abort = true;
        } else if (msg.indexOf("ERROR: none message must be encrypted", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Phase 1 negotiation of IPSec connection has failed. Please check encryption of phase 1 and hash algorithm."));
            GlobalConfig->appendLogEntry(i18n("Phase 1 negotiation of IPSec connection has failed. Please check encryption of phase 1 and hash algorithm.") , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("ERROR: reject the packet, received unexpected payload type 0", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Phase 1 negotiation of IPSec connection has failed. Please check encryption and hash algorithm."));
            GlobalConfig->appendLogEntry(i18n("ERROR: reject the packet, received unexpected payload type 0") , KVpncEnum::error);

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

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

            abort = true;
        } else if (msg.indexOf("ERROR: the peer's certificate is not verified", 0, Qt::CaseInsensitive) > -1) {
            //    KMessageBox::error( this, i18n( "ERROR: the peer's certificate is not verified" ) );
            GlobalConfig->appendLogEntry(i18n("ERROR: the peer's certificate is not verified") , KVpncEnum::error);

            abort = true;
        } else if (msg.indexOf("ignore information because ISAKMP-SAhas not been established yet.", 0, Qt::CaseInsensitive) > -1 || msg.indexOf("ignore information because ISAKMP-SA has not been established yet.", 0, Qt::CaseInsensitive) > -1) {
            //KMessageBox::error( this, i18n( "ERROR: fatal parse failure" ) );
            KMessageBox::error(this, i18n("Phase 2 negotiation of IPSec connection has failed. Please check encryption and hash algorithm."));
            GlobalConfig->appendLogEntry(i18n("Phase 2 negotiation of IPSec connection has failed. Please check encryption and hash algorithm.") , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("has weak file permission", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Wrong file permission. Aborting."));
            GlobalConfig->appendLogEntry(i18n("Wrong file permission. Aborting.") , KVpncEnum::error);

            abort = true;
        } else if (msg.indexOf("IPsec-SA established", 0, Qt::CaseInsensitive) > -1) {
            racoon_tunnel_state++;
            if (racoon_tunnel_state == 1) {
                if (GlobalConfig->KvpncDebugLevel > 1)
                    GlobalConfig->appendLogEntry("[racoon] " + i18n("First tunnel is now up, waiting for second one..."), KVpncEnum::debug);
                if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon && GlobalConfig->currentProfile->getUseLeftSourceIp()) {
                    if ( GlobalConfig->KvpncDebugLevel > 3 )
                        GlobalConfig->appendLogEntry ( i18n ( "Adding virtual IP address" ), KVpncEnum::debug );
                    doAddRemoveVirtualIp("add");
                }
                doPingKickupTunnel();

            } else if (racoon_tunnel_state == 2) {

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

                doIptablesRacoon();
                addRouteRacoon();

                if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon) {
                    if ( GlobalConfig->KvpncDebugLevel > 1 ) {
                        GlobalConfig->appendLogEntry ( "[racoon] " + i18n ( "IPSec phase 2 established." ), KVpncEnum::info );
                    }

                    GlobalConfig->appendLogEntry("[racoon] " + i18n("Connection established."), KVpncEnum::success);

                    sec = hour = min = 0;

                    GlobalConfig->status = KVpncEnum::connected;

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

                    doIptablesRacoon();
                    addRouteRacoon();

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

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

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

            }
        } else if (msg.indexOf("no default route, %defaultroute cannot cope!!!", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("No default route found, necessary for %1." , IpsecType));
            GlobalConfig->appendLogEntry(i18n("No default route found, necessary for %1." , IpsecType) , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("SIOCADDRT: File exists", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry("[racoon err] " + i18n("Setting route failed: route still exists."), KVpncEnum::error);
        } else if (msg.indexOf("SIOCDELRT: File exists", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry("[racoon err] " + i18n("Deleting route failed: route does not exist."), KVpncEnum::error);
        } else if (msg.indexOf("fatal parse failure", 0, Qt::CaseInsensitive) > -1 || msg.indexOf("failed to parse configuration file", 0, Qt::CaseInsensitive) > -1 || msg.indexOf("fatal parse failure", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Error in generated configuration file for \"%1\", please contact the KVpnc team." , QString("racoon")));
            GlobalConfig->appendLogEntry(i18n("Error in generated configuration file for \"%1\", please contact the KVpnc team." , QString("racoon")) , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("ERROR: ", 0, Qt::CaseInsensitive) > -1 && msg.indexOf("algorithm mismatched", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Algorithm mismatched, please select another one."));
            GlobalConfig->appendLogEntry(i18n("[racoon err]: algorithm mismatched, please select another one.") , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("Error: Peer not responding", 0, Qt::CaseInsensitive) > -1) {
            //KMessageBox::error ( this, i18n ( "racoonctl: Peer not responding" )  );
            GlobalConfig->appendLogEntry(i18n("racoonctl: Peer not responding")  , KVpncEnum::error);
            abort = true;
        }
        //  if ( pingtest ) {
        //   // mw->DebugOutput->append( "raw err (pingtest): " + msg );
        //   if ( msg.indexOf( QString("time="), 0, Qt::CaseInsensitive ) > -1 ) {
        //    GlobalConfig->appendLogEntry( "[ping] " + msg, KVpncEnum::success );
        //   } else if ( msg.indexOf( QString("100 % packet loss"), 0, Qt::CaseInsensitive ) > -1 ) {
        //    GlobalConfig->appendLogEntry( "[ping err] " + msg, KVpncEnum::error );
        //   } else {
        //    if ( msg.indexOf( QString("failed to bind"), 0, Qt::CaseInsensitive ) > -1 ) {
        //     KMessageBox::error( this, i18n( "Binding interface failed!" ) );
        //     GlobalConfig->appendLogEntry( i18n( "Binding interface failed!" ) , KVpncEnum::error );
        //    }
        //    if ( msg.indexOf( QString("Destination Host Unreachable"), 0, Qt::CaseInsensitive ) > -1 ) {
        //     KMessageBox::error( this, i18n( "Destination host is unreachable!" ) );
        //     GlobalConfig->appendLogEntry( i18n( "Destination host is unreachable!" ) , KVpncEnum::error );
        //    }
        //   }
        //  }


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


        //  }
    }
}

void KVpnc::readFromStderr_racoon()
{

    bool abort = false;
    QStringList msg_list = QString(RacoonProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        GlobalConfig->appendLogEntry("[racoon err raw] " + msg, KVpncEnum::error);

        // binding to port failed
        if (msg.indexOf("ERROR: failed to bind to address", 0, Qt::CaseInsensitive) > -1  ||   msg.indexOf("ERROR: no address could be bound.", 0, Qt::CaseInsensitive) > -1) {

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

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

                if (Name == "racoon") {

                    //RacoonProcess->setProcessChannelMode ( QProcess::MergedChannels);
                    //disconnect ( RacoonProcess, SIGNAL ( readyReadStandardOutput() ), this, SLOT ( readFromStdout_racoon() ) );
                    //disconnect ( RacoonProcess, SIGNAL ( readyReadStandardError() ), this, SLOT ( readFromStderr_racoon() ) );

                    if (GlobalConfig->doKillRacoonIfStillRunning && abort == false) {
                        if (GlobalConfig->KvpncDebugLevel > 3)
                            GlobalConfig->appendLogEntry(i18n("%1 could not bind to port, trying to kill it...." , QString("racoon")) , KVpncEnum::error);

                        QProcess killracoonprocess(this);
                        QString proc = GlobalConfig->pathToKillall;
                        QStringList args;
                        args.append("racoon");
                        killracoonprocess.setEnvironment(*env);
                        killracoonprocess.start(proc, args);
                        if (!killracoonprocess.waitForStarted()) {
                            GlobalConfig->appendLogEntry(i18n("%1 could not be killed." , QString("racoon")) , KVpncEnum::error);
                            GlobalConfig->appendLogEntry(QString("[racoon err] " + i18n("Bind to given port has failed. Another %1 process is running. Please stop %1 first." , QString("racoon"))) , KVpncEnum::error);
                            abort = true;
                        } else {
                            waitForFinished(&killracoonprocess, 100);
                            sleep(2);

                            // restart racoon
                            //       if ( RacoonProcess != 0)
//               {
//        //        RacoonProcess->kill();
//                delete RacoonProcess;
//                RacoonProcess=0L;
//               }

                            putenv((char*)("LC_ALL=C"));
                            RacoonProcess = new QProcess(this);
                            QString proc = GlobalConfig->pathToRacoon;
                            QStringList args;
                            args.append("-F");    // foreground we want :)
                            //args.append( "-v" );
                            args.append("-f");
                            args.append(tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".conf");
                            //args.append ( "-l" ); // logfile (we get content with tail process)
                            //args.append ( tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log" );
                            if (GlobalConfig->KvpncDebugLevel > 0)
                                GlobalConfig->appendLogEntry("racoon: " + GlobalConfig->pathToRacoon + " -f " + tmpPath + "/racoon" + GlobalConfig->currentProfile->getName() + ".conf", KVpncEnum::debug);


                            //RacoonProcess->setProcessChannelMode(QProcess::MergedChannels);
                            //connect ( RacoonProcess, SIGNAL ( readyReadStandardOutput() ), this, SLOT ( readFromStdout_racoon() ) );
                            //connect ( RacoonProcess, SIGNAL ( readyReadStandardError() ), this, SLOT ( readFromStderr_racoon() ) );

                            RacoonProcess->setEnvironment(*env);
                            RacoonProcess->start(proc, args);
                            if (!RacoonProcess->waitForStarted()) {
                                if (GlobalConfig->KvpncDebugLevel > 0)
                                    GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("racoon")) , KVpncEnum::error);

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

        } else if (msg.indexOf("ERROR: fatal BAD-PROPOSAL-SYNTAX", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Bad proposal from peer reported."));
            GlobalConfig->appendLogEntry(i18n("Bad proposal from peer reported, aborting.") , KVpncEnum::error);

            abort = true;
        } else if (msg.indexOf("ERROR: fatal BAD-PROPOSAL-SYNTAX", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Bad proposal from peer reported."));
            GlobalConfig->appendLogEntry(i18n("Bad proposal from peer reported, aborting.") , KVpncEnum::error);

            abort = true;
        } else if (msg.indexOf("ERROR: couldn't find the pskey for", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("The pre shared key could not be found, check PSK settings."));
            GlobalConfig->appendLogEntry(i18n("PSK is missing, aborting.") , KVpncEnum::error);

            abort = true;
        } else if (msg.indexOf("ERROR: failed to process packet.", 0, Qt::CaseInsensitive) > -1) {
            //   KMessageBox::error( this, i18n( "failed to process packet" ) );
            GlobalConfig->appendLogEntry(i18n("failed to process packet") , KVpncEnum::error);

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

            abort = true;
        } else if (msg.indexOf("ERROR: delete phase1 handle.", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Phase 1 negotiation of IPSec connection has failed. Please check encryption of phase 1 and hash algorithm."));
            GlobalConfig->appendLogEntry(i18n("Phase 1 negotiation of IPSec connection has failed. Please check encryption of phase 1 and hash algorithm.") , KVpncEnum::error);

            abort = true;
        } else if (msg.indexOf("ERROR: none message must be encrypted", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Phase 1 negotiation of IPSec connection has failed. Please check encryption of phase 1 and hash algorithm."));
            GlobalConfig->appendLogEntry(i18n("Phase 1 negotiation of IPSec connection has failed. Please check encryption of phase 1 and hash algorithm.") , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("ERROR: reject the packet, received unexpected payload type 0", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Phase 1 negotiation of IPSec connection has failed. Please check encryption and hash algorithm."));
            GlobalConfig->appendLogEntry(i18n("ERROR: reject the packet, received unexpected payload type 0") , KVpncEnum::error);

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

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

            abort = true;
        } else if (msg.indexOf("ERROR: the peer's certificate is not verified", 0, Qt::CaseInsensitive) > -1) {
            //    KMessageBox::error( this, i18n( "ERROR: the peer's certificate is not verified" ) );
            GlobalConfig->appendLogEntry(i18n("ERROR: the peer's certificate is not verified") , KVpncEnum::error);

            abort = true;
        } else if (msg.indexOf("ignore information because ISAKMP-SAhas not been established yet.", 0, Qt::CaseInsensitive) > -1 || msg.indexOf("ignore information because ISAKMP-SA has not been established yet.", 0, Qt::CaseInsensitive) > -1) {
            //KMessageBox::error( this, i18n( "ERROR: fatal parse failure" ) );
            KMessageBox::error(this, i18n("Phase 2 negotiation of IPSec connection has failed. Please check encryption and hash algorithm."));
            GlobalConfig->appendLogEntry(i18n("Phase 2 negotiation of IPSec connection has failed. Please check encryption and hash algorithm.") , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("has weak file permission", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Wrong file permission. Aborting."));
            GlobalConfig->appendLogEntry(i18n("Wrong file permission. Aborting.") , KVpncEnum::error);

            abort = true;
        } else if (msg.indexOf("IPsec-SA established", 0, Qt::CaseInsensitive) > -1) {
            racoon_tunnel_state++;
            if (racoon_tunnel_state == 1) {
                if (GlobalConfig->KvpncDebugLevel > 1)
                    GlobalConfig->appendLogEntry("[racoon] " + i18n("First tunnel is now up, waiting for second one..."), KVpncEnum::debug);
            } else if (racoon_tunnel_state == 2) {

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

                doIptablesRacoon();
                addRouteRacoon();

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

                    sec = hour = min = 0;

                    GlobalConfig->status = KVpncEnum::connected;

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

                    doIptablesRacoon();
                    addRouteRacoon();

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

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

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

            }
        } else if (msg.indexOf("no default route, %defaultroute cannot cope!!!", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("No default route found, necessary for %1." , IpsecType));
            GlobalConfig->appendLogEntry(i18n("No default route found, necessary for %1." , IpsecType) , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("SIOCADDRT: File exists", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry("[racoon err] " + i18n("Setting route failed: route still exists."), KVpncEnum::error);
        } else if (msg.indexOf("SIOCDELRT: File exists", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry("[racoon err] " + i18n("Deleting route failed: route does not exist."), KVpncEnum::error);
        } else if (msg.indexOf("fatal parse failure", 0, Qt::CaseInsensitive) > -1 || msg.indexOf("failed to parse configuration file", 0, Qt::CaseInsensitive) > -1 || msg.indexOf("fatal parse failure", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Error in generated configuration file for \"%1\", please contact the KVpnc team." , QString("racoon")));
            GlobalConfig->appendLogEntry(i18n("Error in generated configuration file for \"%1\", please contact the KVpnc team." , QString("racoon")) , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("ERROR: ", 0, Qt::CaseInsensitive) > -1 && msg.indexOf("algorithm mismatched", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Algorithm mismatched, please select another one."));
            GlobalConfig->appendLogEntry(i18n("[racoon err]: algorithm mismatched, please select another one.") , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("Error: Peer not responding", 0, Qt::CaseInsensitive) > -1) {
            //KMessageBox::error ( this, i18n ( "racoonctl: Peer not responding" )  );
            GlobalConfig->appendLogEntry(i18n("racoonctl: Peer not responding")  , KVpncEnum::error);
            abort = true;
        }
        //  if ( pingtest ) {
        //   // mw->DebugOutput->append( "raw err (pingtest): " + msg );
        //   if ( msg.indexOf( QString("time="), 0, Qt::CaseInsensitive ) > -1 ) {
        //    GlobalConfig->appendLogEntry( "[ping] " + msg, KVpncEnum::success );
        //   } else if ( msg.indexOf( QString("100 % packet loss"), 0, Qt::CaseInsensitive ) > -1 ) {
        //    GlobalConfig->appendLogEntry( "[ping err] " + msg, KVpncEnum::error );
        //   } else {
        //    if ( msg.indexOf( QString("failed to bind"), 0, Qt::CaseInsensitive ) > -1 ) {
        //     KMessageBox::error( this, i18n( "Binding interface failed!" ) );
        //     GlobalConfig->appendLogEntry( i18n( "Binding interface failed!" ) , KVpncEnum::error );
        //    }
        //    if ( msg.indexOf( QString("Destination Host Unreachable"), 0, Qt::CaseInsensitive ) > -1 ) {
        //     KMessageBox::error( this, i18n( "Destination host is unreachable!" ) );
        //     GlobalConfig->appendLogEntry( i18n( "Destination host is unreachable!" ) , KVpncEnum::error );
        //    }
        //   }
        //  }

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

    }
}

void KVpnc::readFromStdout_racoon_helper()
{
    if (RacoonHelperProcess) {
        QStringList ProcessMsg_connect_raw_list = QString(RacoonHelperProcess->readAllStandardOutput()).split('\n');
        for (QStringList::Iterator it = ProcessMsg_connect_raw_list.begin(); it != ProcessMsg_connect_raw_list.end(); ++it) {
            QString ProcessMsg_connect = *it;
            if (GlobalConfig->KvpncDebugLevel > 3)
                GlobalConfig->appendLogEntry("[racoon helper] " + ProcessMsg_connect, KVpncEnum::debug);
        }
    }
}

void KVpnc::readFromStderr_racoon_helper()
{

    bool abort = false;
    if (RacoonHelperProcess) {
        QStringList ProcessMsg_connect_raw_list = QString(RacoonHelperProcess->readAllStandardError()).split('\n');
        for (QStringList::Iterator it = ProcessMsg_connect_raw_list.begin(); it != ProcessMsg_connect_raw_list.end(); ++it) {
            QString ProcessMsg_connect = *it;
            GlobalConfig->appendLogEntry("[racoon helper err] " + ProcessMsg_connect, KVpncEnum::error);

            bool wrong_algo = false;

            if (ProcessMsg_connect.indexOf("libipsec: syntax error while parsing", 0, Qt::CaseInsensitive) > -1 && !wrong_algo) {
                KMessageBox::error(this, i18n("Error in generated configuration file for %1\", please contact the KVpnc team." , QString("setkey")));
                GlobalConfig->appendLogEntry(i18n("libipsec has found syntax error while parsing.")  , KVpncEnum::error);
                abort = true;
            }
            // 		if ( ProcessMsg_connect.indexOf ( "algorithm mismatched") > -1)
            // 		{
            // 		KMessageBox::error ( this, i18n ( "Algorithms mismatched. Please select other values for authentication and encryption." , "setkey" ) );
            // 		GlobalConfig->appendLogEntry ( i18n ( "Algorithms mismatched. Please select other values for authentication and encryption." ) , KVpncEnum::error );
            // 		wrong_algo = true;
            // 		abort = true;
            // 		}
            if (ProcessMsg_connect.indexOf("invalid IP address", 0, Qt::CaseInsensitive) > -1)
            {
                KMessageBox::error ( this, i18n ( "invalid IP address", QString("setkey") ) );
                GlobalConfig->appendLogEntry ( i18n ( "invalid IP address" ) , KVpncEnum::error );
                wrong_algo = true;
                abort = true;
            }

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

void KVpnc::readFromStdout_ipsec()
{
    QStringList msg_list = QString(IpsecStartProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString ProcessMsg_connect = msg_list.at(i);

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

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

            if (ProcessMsg_connect.indexOf("time=", 0, Qt::CaseInsensitive) > -1) {
                GlobalConfig->appendLogEntry("[ping] " + ProcessMsg_connect, KVpncEnum::success);
            } else if (ProcessMsg_connect.indexOf("100 % packet loss", 0, Qt::CaseInsensitive) > -1) {
                NormalMsg = false;
                GlobalConfig->appendLogEntry("[ping err] " + ProcessMsg_connect, KVpncEnum::error);
            } else {
                if (ProcessMsg_connect.indexOf("Destination Host Unreachable", 0, Qt::CaseInsensitive) > -1) {
                    NormalMsg = false;
                    KMessageBox::error(this, i18n("Destination host is unreachable."));
                    GlobalConfig->appendLogEntry(i18n("Destination host is unreachable."), KVpncEnum::error);
                }
            }
        } else {
            // FATAL ERROR:
            if (ProcessMsg_connect.indexOf("failed to bind", 0, Qt::CaseInsensitive) > -1 || ProcessMsg_connect.indexOf("Address already in use", 0, Qt::CaseInsensitive) > -1) {
                QString NameAndPid = Utils(GlobalConfig).getNameAndPidOfProgramListen(500);
                GlobalConfig->appendLogEntry(i18n("NameAndPid: %1" , NameAndPid) , KVpncEnum::debug);
                int pid = -1;
                QString Name = "";
                if (!NameAndPid.isEmpty()) {
                    pid = NameAndPid.section('/', 0, 0).toInt();
                    Name = NameAndPid.section('/', 1, 1);
                    KMessageBox::error(this, i18n("Binding port %1 failed. Program \"%2\" with PID \"%3\" is using it. You have to stop it first." , QString().setNum(500) , Name , QString().setNum(pid)));
                } else
                    KMessageBox::error(this, i18n("Port binding failed"));
                GlobalConfig->appendLogEntry(i18n("Port binding failed") , KVpncEnum::error);
                abort = true;
                IpsecGotError = true;
                IpsecWhackStatusTimer.stop();
            } else if ( ProcessMsg_connect.indexOf ( "error fetching interface information: Device not found", 0, Qt::CaseInsensitive ) > -1 ) {
                QString interfacemissing = ProcessMsg_connect.section(" ", 1,1).replace(':', "");
                KMessageBox::error ( this, i18n ( "Specified network device (%1) does not exist. Please specify an existing device or default at settings.", interfacemissing) );
                GlobalConfig->appendLogEntry ( i18n ( "Specified network device (%1) does not exist. Please specify an existing device or default at settings." , interfacemissing) , KVpncEnum::error );
                abort = true;
                IpsecGotError = true;
                IpsecWhackStatusTimer.stop();
            } else if (ProcessMsg_connect.indexOf("apparently already active", 0, Qt::CaseInsensitive) > -1 ||  ProcessMsg_connect.indexOf("ipsec_setup: Openswan IPsec apparently already active, start aborted", 0, Qt::CaseInsensitive) > -1) {
                //    KMessageBox::error ( this, i18n ( "Unsupported card found. Please use a smartcard with openct support. This is a Openswan limitation, sorry." ) );
                GlobalConfig->appendLogEntry(i18n("Openswan seems still running, restart it.") , KVpncEnum::info);
                //    abort = true;
                startStopIpsec(true);
                sleep(5);
                startStopIpsec();
                if ( !IpsecGotError)
                    ipsecStarted(0,QProcess::NormalExit);
            }

            else if (ProcessMsg_connect.indexOf("no default route, %defaultroute cannot cope!!!", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("No default route found, necessary for %1." , IpsecType));
                GlobalConfig->appendLogEntry(i18n("No default route found, necessary for %1." , IpsecType) , KVpncEnum::error);
                abort = true;
                ErrorMsg = true;
            }
        }

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

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

void KVpnc::readFromStderr_ipsec()
{
    bool abort = false;
    QStringList msg_list = QString(IpsecStartProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString ProcessMsg_connect = msg_list.at(i);

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

        else if (ProcessMsg_connect.indexOf("error loading RSA private key file", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry("[ipsec err] " + i18n("RSA private key file could not be loaded."), KVpncEnum::error);
            abort = true;
            IpsecGotError = true;
            IpsecWhackStatusTimer.stop();
        } else if (ProcessMsg_connect.indexOf("unable to start strongSwan -- fatal errors in config", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Unable to start strongSwan -- fatal errors in config. Please contact the KVpnc author."));
            GlobalConfig->appendLogEntry("[ipsec err] " + i18n("Unable to start strongSwan -- fatal errors in config. Please contact the KVpnc author."), KVpncEnum::error);
            abort = true;
            IpsecGotError = true;
            IpsecWhackStatusTimer.stop();
        } else if (ProcessMsg_connect.indexOf("Starting strongSwan", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry("[ipsec] " + ProcessMsg_connect, KVpncEnum::info);
        } else if (ProcessMsg_connect.indexOf("apparently already active", 0, Qt::CaseInsensitive) > -1 || ProcessMsg_connect.indexOf("Openswan IPsec apparently already active, start aborted", 0, Qt::CaseInsensitive) > -1) {
//    KMessageBox::error ( this, i18n ( "Unsupported card found. Please use a smartcard with openct support. This is an Openswan limitation, sorry." ) );
            GlobalConfig->appendLogEntry(i18n("Openswan seems to be still running, restart it.") , KVpncEnum::error);
//    abort = true;
            startStopIpsec(true);
            sleep(5);
            startStopIpsec();
            if ( !IpsecGotError)
                ipsecStarted(0,QProcess::NormalExit);
        } else if (pingtest) {
            // mw->DebugOutput->append( "raw err (pingtest): " + ProcessMsg_connect );
            if (ProcessMsg_connect.indexOf("time=", 0, Qt::CaseInsensitive) > -1) {
                GlobalConfig->appendLogEntry("[ping] " + ProcessMsg_connect, KVpncEnum::success);
            } else if (ProcessMsg_connect.indexOf("100 % packet loss", 0, Qt::CaseInsensitive) > -1) {
                GlobalConfig->appendLogEntry("[ping err] " + ProcessMsg_connect, KVpncEnum::error);
            } else {
                if (ProcessMsg_connect.indexOf("failed to bind", 0, Qt::CaseInsensitive) > -1) {
                    KMessageBox::error(this, i18n("Binding interface failed."));
                    GlobalConfig->appendLogEntry(i18n("Binding interface failed.") , KVpncEnum::error);
                }
                if (ProcessMsg_connect.indexOf("Destination Host Unreachable", 0, Qt::CaseInsensitive) > -1) {
                    KMessageBox::error(this, i18n("Destination host is unreachable."));
                    GlobalConfig->appendLogEntry(i18n("Binding interface failed.") , KVpncEnum::error);
                }
            }
        } else {
            GlobalConfig->appendLogEntry("[ipsec err] " + ProcessMsg_connect, KVpncEnum::error);
        }

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

void KVpnc::readFromStdout_ipsecwhack()
{
    QStringList msg_list = QString(IpsecWhackProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

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

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

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

            IpsecWhackProcess->write(GlobalConfig->TmpUsername.toUtf8());
            IpsecWhackProcess->write("\n");
        } else if (msg.indexOf("prompt for Password:", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->KvpncDebugLevel > 1)
                GlobalConfig->appendLogEntry(i18n("XAUTH password requested, send it...") , KVpncEnum::debug);
            if (GlobalConfig->KvpncDebugLevel > 5)
                GlobalConfig->appendLogEntry(i18n("XAUTH password: %1" , QString(GlobalConfig->TmpPassword)) , KVpncEnum::debug);

            IpsecWhackProcess->write(GlobalConfig->TmpPassword.toUtf8());
            IpsecWhackProcess->write("\n");
        } else if (msg.indexOf("listening for IKE messages", 0, Qt::CaseInsensitive) > -1) {
            // strongswan after ipsec whack --listen
            /*   disconnect ( IpsecWhackProcess, SIGNAL ( readyReadStandardOutput() ), this, SLOT ( readFromStdout_ipsecwhack() ) );
               disconnect ( IpsecWhackProcess, SIGNAL ( readyReadStandardError() ), this, SLOT ( readFromStderr_ipsecwhack() ) );
               delete IpsecWhackProcess;*/
            putenv((char*)("LC_ALL=C"));
            IpsecWhackProcess = new QProcess(this);
            QString proc = GlobalConfig->pathToIpsec;
            QStringList args;
            args.append("whack");
            args.append("--name");
            args.append(GlobalConfig->currentProfile->getName());
            args.append("--initiate");

            connect(IpsecWhackProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhack()));
            connect(IpsecWhackProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhack()));
            connect(IpsecWhackProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(ipsecwhack_exited(int, QProcess::ExitStatus)));

            IpsecWhackProcess->setEnvironment(*env);
            IpsecWhackProcess->start(proc, args);
            if (!IpsecWhackProcess->waitForStarted()) {
                disconnect(IpsecWhackProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhack()));
                disconnect(IpsecWhackProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhack()));
                disconnect(IpsecWhackProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(ipsecwhack_exited(int, QProcess::ExitStatus)));
                delete IpsecWhackProcess;
                IpsecWhackProcess = 0L;
                KMessageBox::error(this, i18n("Failed to start \"%1\"." , QString(GlobalConfig->pathToIpsec + " whack' --name " + GlobalConfig->currentProfile->getName() + " --initiate")));
                GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString(GlobalConfig->pathToIpsec + " whack' --name " + GlobalConfig->currentProfile->getName() + " --initiate")) , KVpncEnum::error);
                disconnectClicked();
            } else {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("\"%1\" started.", QString(GlobalConfig->pathToIpsec + " whack --name " + GlobalConfig->currentProfile->getName() + " --initiate")), KVpncEnum::debug);
            }
        } else if (msg.indexOf("added connection", 0, Qt::CaseInsensitive) > -1) {
//    XAUTH
            if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()) {
                ToolInfo *IpsecToolInfo = Utils(GlobalConfig).getToolInfo("ipsec") ;
                if (IpsecToolInfo->Version.contains("Openswan" , Qt::CaseInsensitive)) {
                    sleep(3);
                    //openswan
                    putenv((char*)("LC_ALL=C"));
                    IpsecWhackProcess = new QProcess(this);
                    QString proc = GlobalConfig->pathToIpsec;
                    QStringList args;
                    args.append("whack");
                    args.append("--name");
                    args.append(GlobalConfig->currentProfile->getName());
                    args.append("--initiate");

                    connect(IpsecWhackProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhack()));
                    connect(IpsecWhackProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhack()));
                    connect(IpsecWhackProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(ipsecwhack_exited(int, QProcess::ExitStatus)));

                    QString LogPassword = "";
                    if (GlobalConfig->KvpncDebugLevel > 5)
                        LogPassword = GlobalConfig->TmpPassword;
                    else
                        LogPassword = "*****";
                    IpsecWhackProcess->setEnvironment(*env);
                    IpsecWhackProcess->start(proc, args);
                    if (!IpsecWhackProcess->waitForStarted()) {
                        disconnect(IpsecWhackProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhack()));
                        disconnect(IpsecWhackProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhack()));
                        disconnect(IpsecWhackProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(ipsecwhack_exited(int, QProcess::ExitStatus)));
                        delete IpsecWhackProcess;
                        IpsecWhackProcess = 0L;
                        KMessageBox::error(this, i18n("Failed to start \"%1\".", QString(GlobalConfig->pathToIpsec + " whack' --name " + GlobalConfig->currentProfile->getName() + " --initiate")));
                        GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\".", QString(GlobalConfig->pathToIpsec + " whack' --name " + GlobalConfig->currentProfile->getName() + " --initiate")) , KVpncEnum::error);
                        disconnectClicked();
                    } else {
                        if (GlobalConfig->KvpncDebugLevel > 0)
                            GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString(GlobalConfig->pathToIpsec + " whack --name " + GlobalConfig->currentProfile->getName() + " --initiate")), KVpncEnum::debug);
                    }
                }
            }

        } else if (msg.indexOf("XAUTH: Successfully Authenticated", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry(i18n("Authentication succeeded.") , KVpncEnum::info);
        } else if (msg.indexOf("parsing XAUTH status", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->WaitingForXauth = true;
        } else if (msg.indexOf("added connection", 0, Qt::CaseInsensitive) > -1) {
//    XAUTH
            if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()) {
                ToolInfo *IpsecToolInfo = Utils(GlobalConfig).getToolInfo("ipsec") ;
                if (IpsecToolInfo->Version.contains("Openswan", Qt::CaseInsensitive)) {
                    sleep(3);
                    //openswan
                    putenv((char*)("LC_ALL=C"));
                    IpsecWhackProcess = new QProcess(this);
                    QString proc = GlobalConfig->pathToIpsec;
                    QStringList args;
                    args.append("whack");
                    args.append("--name");
                    args.append(GlobalConfig->currentProfile->getName());
                    args.append("--initiate");

                    connect(IpsecWhackProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhack()));
                    connect(IpsecWhackProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhack()));
                    connect(IpsecWhackProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(ipsecwhack_exited(int, QProcess::ExitStatus)));

                    QString LogPassword = "";
                    if (GlobalConfig->KvpncDebugLevel > 5)
                        LogPassword = GlobalConfig->TmpPassword;
                    else
                        LogPassword = "*****";
                    IpsecWhackProcess->setEnvironment(*env);
                    IpsecWhackProcess->start(proc, args);
                    if (!IpsecWhackProcess->waitForStarted()) {
                        disconnect(IpsecWhackProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhack()));
                        disconnect(IpsecWhackProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhack()));
                        disconnect(IpsecWhackProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(ipsecwhack_exited(int, QProcess::ExitStatus)));
                        delete IpsecWhackProcess;
                        IpsecWhackProcess = 0L;
                        KMessageBox::error(this, i18n("Failed to start \"%1\".", QString(GlobalConfig->pathToIpsec + " whack' --name " + GlobalConfig->currentProfile->getName() + " --initiate")));
                        GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString(GlobalConfig->pathToIpsec + " whack' --name " + GlobalConfig->currentProfile->getName() + " --initiate")) , KVpncEnum::error);
                        disconnectClicked();
                    } else {
                        if (GlobalConfig->KvpncDebugLevel > 0)
                            GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString(GlobalConfig->pathToIpsec + " whack --name " + GlobalConfig->currentProfile->getName() + " --initiate")), KVpncEnum::debug);
                    }
                }
            }

        } else if ( msg.indexOf ("ISAKMP SA established", 0, Qt::CaseInsensitive ) > -1 ) {
            if (IpsecPhase2Up)
                return;

            if (IpsecPhase1Up)
                return;
            else
                IpsecPhase1Up=true;

            timer.stop();
            IpsecWhackStatusTimer.stop();
            abort = false;
            if (GlobalConfig->KvpncDebugLevel > 1) {
                if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan ) {
                    GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "IPSec phase 1 established." ), KVpncEnum::info );
                }
                else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan ) {
                    GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "Low level IPsec phase 1 established." ), KVpncEnum::info );
                }
            }
        } else if (msg.indexOf("IPsec SA established", 0, Qt::CaseInsensitive) > -1) {
            ipsecPhase2Established();
        } else if (msg.indexOf("XAUTH: Successfully Authenticated", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry(i18n("Authentication succeeded.") , KVpncEnum::info);
        } else if (msg.indexOf("apparently already active", 0, Qt::CaseInsensitive) > -1) {
//    KMessageBox::error ( this, i18n ( "Openswan seems still running, restart it." ) );
            GlobalConfig->appendLogEntry(i18n("Openswan seems still running, restart it.") , KVpncEnum::info);
//       abort = true;
            startStopIpsec(true);
            sleep(5);
            startStopIpsec();
            if ( !IpsecGotError)
                ipsecStarted(0,QProcess::NormalExit);
        } else if (msg.indexOf("no default route, %defaultroute cannot cope!!!", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("No default route found, necessary for %1." , QString(IpsecType)));
            GlobalConfig->appendLogEntry(i18n("No default route found, necessary for %1." , QString(IpsecType)) , KVpncEnum::error);
            abort = true;
            ErrorMsg = true;
            IpsecGotError = true;
            IpsecWhackStatusTimer.stop();
        } else if (msg.indexOf("ignoring informational payload, type NO_PROPOSAL_CHOSEN", 0, Qt::CaseInsensitive) > -1) {
            if (!stopContinue) {
                KMessageBox::error(this, i18n("Wrong connection parameters used. Please verify the connection settings."));
                GlobalConfig->appendLogEntry(i18n("Peer reported that we use wrong connection parameters.") , KVpncEnum::error);
                abort = true;
                stopContinue = true;
                IpsecGotError = true;
                IpsecWhackStatusTimer.stop();
            }
        } else if (msg.indexOf("perhaps peer likes no proposal", 0, Qt::CaseInsensitive) > -1) {
            if (!stopContinue) {
                KMessageBox::error(this, i18n("Wrong connection parameters used. Please verify in IPSec settings."));
                GlobalConfig->appendLogEntry(i18n("Peer reported that we use wrong connection parameters.") , KVpncEnum::error);
                abort = true;
                stopContinue = true;
                IpsecGotError = true;
                IpsecWhackStatusTimer.stop();
            }
        } else if (msg.indexOf("INVALID_ID_INFORMATION", 0, Qt::CaseInsensitive) > -1) {
            if (!stopContinue) {
                KMessageBox::error(this, i18n("Peer refused ID settings. Please verify the local ID in IPsec and remote network in Network - General settings."));
                GlobalConfig->appendLogEntry(i18n("Peer refused ID settings. Please verify the local ID in IPsec and remote network in Network - General settings.") , KVpncEnum::error);
                abort = true;
                stopContinue = true;
                IpsecGotError = true;
                IpsecWhackStatusTimer.stop();
            }
        } else if (msg.indexOf("cannot initiate connection with ID wildcards", 0, Qt::CaseInsensitive) > -1) {
            if (!stopContinue) {
                KMessageBox::error(this, i18n("Cannot initiate connection with ID wildcards. Please verify the connection settings."));
                GlobalConfig->appendLogEntry(i18n("Cannot initiate connection with ID wildcards.") , KVpncEnum::error);
                abort = true;
                stopContinue = true;
                IpsecGotError = true;
                IpsecWhackStatusTimer.stop();
            }
        } else if (msg.indexOf(QString("Can not opportunistically initiate"), 0, Qt::CaseInsensitive) > -1) {
            if (!stopContinue) {
                KMessageBox::error(this, i18n("Cannot opportunistically initiate. Please verify the connection settings."));
                GlobalConfig->appendLogEntry(i18n("Cannot opportunistically initiate.") , KVpncEnum::error);
                abort = true;
                stopContinue = true;
                IpsecGotError = true;
                IpsecWhackStatusTimer.stop();
            }
        } else if (msg.indexOf("unable to locate my private key", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Private key could not be found. Please check certificate settings."));
            GlobalConfig->appendLogEntry(i18n("Private key could not be found. Please check certificate settings.") , KVpncEnum::error);
            abort = true;
            IpsecGotError = true;
            IpsecWhackStatusTimer.stop();
        } else if (msg.indexOf("SMARTCARD support is deactivated in pluto/Makefile", 0, Qt::CaseInsensitive) > -1 || msg.indexOf("Smartcard not supported", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("SMARTCARD support is deactivated. Please enable smartcard support in %1 package" , QString(IpsecType)));
            GlobalConfig->appendLogEntry(i18n("SMARTCARD support is deactivated. Please enable smartcard support in %1 package" , QString(IpsecType)) , KVpncEnum::error);
            abort = true;
            IpsecGotError = true;
            IpsecWhackStatusTimer.stop();
        } else if (msg.indexOf("Unsupported card", 0, Qt::CaseInsensitive) > -1 &&  msg.indexOf("pkcs15", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Unsupported card found. Please use a smartcard with openct support. This is a Openswan limitation, sorry."));
            GlobalConfig->appendLogEntry(i18n("Unsupported card found. Please use a smartcard with openct support. This is a Openswan limitation, sorry.") , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("we require peer to have ID", 0, Qt::CaseInsensitive) > -1 && msg.indexOf("but peer declares", 0, Qt::CaseInsensitive) > -1) {
            QString PeerID = msg.section('\'', 3, 3);
            QString OurID = msg.section('\'', 1, 1);
            KMessageBox::error(this, i18n("Wrong ID \"%1\" from peer, expected \"%2\"." , QString(PeerID), OurID));
            GlobalConfig->appendLogEntry(i18n("Wrong ID \"%1\" from peer, expected \"%2\"." , QString(PeerID) , OurID) , KVpncEnum::error);
            int result = KMessageBox::questionYesNo(this, i18n("Do you want to use \"%1\" instead of \"%2\" as remote ID and reconnect?", QString(PeerID), OurID), i18n("Fix remote ID?"));
            if (result == 3) { // Yes
                disconnectClicked();
                GlobalConfig->currentProfile->setUseSpecialRemoteID(true);
                GlobalConfig->currentProfile->setSpecialRemoteID(PeerID);
                GlobalConfig->currentProfile->setRemoteIDType("user");
                saveSessionClicked();
                connectClicked();
            } else {
                if (!stopContinue) {

                    abort = true;
                    stopContinue = true;
                }
            }
        }
        else if ( msg.indexOf( "no connection named", 0 , Qt::CaseInsensitive ) > -1 )
        {
            KMessageBox::error ( this, i18n ( "Connection not found. This seems like the configuration is invalid or too fast connect/disconnect." ) );
            GlobalConfig->appendLogEntry ( i18n ( "Connection not found. This seems like the configuration is invalid or too fast connect/disconnect." ) , KVpncEnum::error );
            abort = true;
            IpsecGotError = true;
            IpsecWhackStatusTimer.stop();
        }
        else if ( msg.indexOf( "deleting state (STATE_QUICK_I1)", 0 , Qt::CaseInsensitive ) > -1 || msg.indexOf( "deleting state (STATE_MAIN_I3)", 0 , Qt::CaseInsensitive ) > -1  || msg.indexOf( "deleting state (STATE_MAIN_I2)", 0 , Qt::CaseInsensitive ) > -1  )
        {
            //KMessageBox::error ( this, i18n ( "Phase 1 was deleted. Disconnecting." );
            GlobalConfig->appendLogEntry ( i18n ( "Phase 1 was deleted. Disconnecting." ) , KVpncEnum::error );
            abort = true;
            IpsecGotError = true;
            IpsecWhackStatusTimer.stop();
        }


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

        if (abort) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("There is a reason to stop connecting, terminating \"%1\" process.", QString("ipsec whack --listen")) , KVpncEnum::debug);
            disconnectClicked();
            GlobalConfig->status = KVpncEnum::disconnected;
            setGuiStatus(KVpncEnum::disconnected);
            return ;
        }

    }

}

void KVpnc::readFromStderr_ipsecwhack()
{
    QStringList msg_list = QString(IpsecWhackProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        bool ErrorMsg = false;
        bool abort = false;

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

//   // binding to port failed
//   if ( msg.indexOf ( "ERROR: failed to bind to address", 0, Qt::CaseInsensitive ) > -1 )
//   {

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


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

        else if (msg.indexOf("no default route, %defaultroute cannot cope!!!", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("No default route found, necessary for %1.", QString(IpsecType)));
            GlobalConfig->appendLogEntry(i18n("No default route found, necessary for %1." , QString(IpsecType)) , KVpncEnum::error);
            abort = true;
            ErrorMsg = true;
            IpsecGotError = true;
            IpsecWhackStatusTimer.stop();
        } else if (msg.indexOf("ignoring informational payload, type NO_PROPOSAL_CHOSEN", 0, Qt::CaseInsensitive) > -1) {
            if (!stopContinue) {
                KMessageBox::error(this, i18n("Wrong connection parameters used. Please verify the connection settings."));
                GlobalConfig->appendLogEntry(i18n("Peer reported that we use wrong connection parameters.") , KVpncEnum::error);
                abort = true;
                stopContinue = true;
                IpsecGotError = true;
                IpsecWhackStatusTimer.stop();
            }
        } else if (msg.indexOf("perhaps peer likes no proposal", 0, Qt::CaseInsensitive) > -1) {
            if (!stopContinue) {
                KMessageBox::error(this, i18n("Wrong connection parameters used. Please verify in IPSec settings."));
                GlobalConfig->appendLogEntry(i18n("Peer reported that we use wrong connection parameters.") , KVpncEnum::error);
                abort = true;
                stopContinue = true;
                IpsecGotError = true;
                IpsecWhackStatusTimer.stop();
            }
        } else if (msg.indexOf("INVALID_ID_INFORMATION", 0, Qt::CaseInsensitive) > -1) {
            if (!stopContinue) {
                KMessageBox::error(this, i18n("Peer refused ID settings. Please verify the local ID in IPsec and remote network in Network - General settings."));
                GlobalConfig->appendLogEntry(i18n("Peer refused ID settings. Please verify the local ID in IPsec and remote network in Network - General settings.") , KVpncEnum::error);
                abort = true;
                stopContinue = true;
                IpsecGotError = true;
                IpsecWhackStatusTimer.stop();
            }
        } else if (msg.indexOf("cannot initiate connection with ID wildcards", 0, Qt::CaseInsensitive) > -1) {
            if (!stopContinue) {
                KMessageBox::error(this, i18n("Cannot initiate connection with ID wildcards. Please verify the connection settings."));
                GlobalConfig->appendLogEntry(i18n("Cannot initiate connection with ID wildcards.") , KVpncEnum::error);
                abort = true;
                stopContinue = true;
                IpsecGotError = true;
                IpsecWhackStatusTimer.stop();
            }
        } else if (msg.indexOf(QString("Can not opportunistically initiate"), 0, Qt::CaseInsensitive) > -1) {
            if (!stopContinue) {
                KMessageBox::error(this, i18n("Cannot opportunistically initiate. Please verify the connection settings."));
                GlobalConfig->appendLogEntry(i18n("Cannot opportunistically initiate.") , KVpncEnum::error);
                abort = true;
                stopContinue = true;
                IpsecGotError = true;
                IpsecWhackStatusTimer.stop();
            }
        } else if (msg.indexOf("unable to locate my private key", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Private key could not be found. Please check certificate settings."));
            GlobalConfig->appendLogEntry(i18n("Private key could not be found. Please check certificate settings.") , KVpncEnum::error);
            abort = true;
            IpsecGotError = true;
            IpsecWhackStatusTimer.stop();
        } else if (msg.indexOf("SMARTCARD support is deactivated in pluto/Makefile", 0, Qt::CaseInsensitive) > -1 || msg.indexOf("Smartcard not supported", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("SMARTCARD support is deactivated. Please enable smartcard support in %1 package", QString(IpsecType)));
            GlobalConfig->appendLogEntry(i18n("SMARTCARD support is deactivated. Please enable smartcard support in %1 package", QString(IpsecType)) , KVpncEnum::error);
            abort = true;
            IpsecGotError = true;
            IpsecWhackStatusTimer.stop();
        } else if (msg.indexOf("Unsupported card", 0, Qt::CaseInsensitive) > -1 &&  msg.indexOf("pkcs15", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Unsupported card found. Please use a smartcard with openct support. This is a Openswan limitation, sorry."));
            GlobalConfig->appendLogEntry(i18n("Unsupported card found. Please use a smartcard with openct support. This is a Openswan limitation, sorry.") , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("we require peer to have ID", 0, Qt::CaseInsensitive) > -1 && msg.indexOf("but peer declares", 0, Qt::CaseInsensitive) > -1) {
            QString PeerID = msg.section('\'', 3, 3);
            QString OurID = msg.section('\'', 1, 1);
            KMessageBox::error(this, i18n("Wrong ID \"%1\" from peer, expected \"%2\"." , QString(PeerID), OurID));
            GlobalConfig->appendLogEntry(i18n("Wrong ID \"%1\" from peer, expected \"%2\"." , QString(PeerID), OurID) , KVpncEnum::error);
            int result = KMessageBox::questionYesNo(this, i18n("Do you want to use \"%1\" instead of \"%2\" as remote ID and reconnect?", QString(PeerID), OurID), i18n("Fix remote ID?"));
            if (result == 3) { // Yes
                disconnectClicked();
                GlobalConfig->currentProfile->setUseSpecialRemoteID(true);
                GlobalConfig->currentProfile->setSpecialRemoteID(PeerID);
                GlobalConfig->currentProfile->setRemoteIDType("user");
                saveSessionClicked();
                connectClicked();
            } else {
                if (!stopContinue) {

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

void KVpnc::readFromStdout_ipsecwhacklisten()
{
    if (IpsecWhackListenProcess == 0 || IpsecGotError)
        return;
    QStringList msg_list = QString(IpsecWhackListenProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        bool abort = false;

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

        if (msg.indexOf("listening for IKE messages", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->KvpncDebugLevel > 3)
                GlobalConfig->appendLogEntry("[ipsec whack listen] " + i18n("Listen was successful."), KVpncEnum::debug);
            start_ipsec_initiate();
        } else if (msg.indexOf("ISAKMP SA established", 0, Qt::CaseInsensitive) > -1 || msg.indexOf("transition from state STATE_QUICK_I1 to state STATE_QUICK_I2", 0, Qt::CaseInsensitive) > -1 ) {

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

            if (IpsecPhase1Up)
                return;
            else
                IpsecPhase1Up = true;
            timer.stop();
            IpsecWhackStatusTimer.stop();
            abort = false;
            if (GlobalConfig->KvpncDebugLevel > 1) {
                if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan) {
                    GlobalConfig->appendLogEntry("[ipsec] " + i18n("IPSec phase 1 established."), KVpncEnum::info);
                } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
                    GlobalConfig->appendLogEntry("[ipsec] " + i18n("Low level IPsec phase 1 established."), KVpncEnum::info);
                }
            }
            if (GlobalConfig->currentProfile->getUseLeftSourceIp()) {
                if ( GlobalConfig->KvpncDebugLevel > 3 )
                    GlobalConfig->appendLogEntry ( i18n ( "Adding virtual IP address" ), KVpncEnum::debug );
                doAddRemoveVirtualIp("add");
            }
            doPingKickupTunnel();


        } else if (msg.indexOf("IPsec SA established", 0, Qt::CaseInsensitive) > -1) {
            timer.stop();
            IpsecWhackStatusTimer.stop();

            if (IpsecPhase2Up)
                return;
            else
                IpsecPhase2Up = true;
            abort = false;

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

            if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan) {
                GlobalConfig->appendLogEntry("[ipsec] " + i18n("Connection established."), KVpncEnum::success);
            } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
                GlobalConfig->appendLogEntry("[ipsec] " + i18n("Low level IPsec connection established."), KVpncEnum::success);
            }

            doIptablesFreeswan();
            addRouteIpsec();

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

                GlobalConfig->status = KVpncEnum::connected;

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


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

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

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



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

//   if ( abort )
//   {
        //			IpsecGotError = true;
        //			IpsecWhackStatusTimer.stop();
//    if ( GlobalConfig->KvpncDebugLevel > 0 )
//     GlobalConfig->appendLogEntry ( i18n ( "There is a reason to stop connecting, terminating \"%1\" process.", QString( "ipsec whack --listen" )) , KVpncEnum::debug );
//    disconnectClicked();
//    GlobalConfig->status = KVpncEnum::disconnected;
//    setGuiStatus ( disconnected );
//    return ;
//   }
    }
}

void KVpnc::readFromStderr_ipsecwhacklisten()
{
    if ( IpsecWhackListenProcess ==0  || IpsecGotError )
        return;

    bool abort = false;
    QStringList msg_list = QString(IpsecWhackListenProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
//   GlobalConfig->appendLogEntry ( "[ipsec whack listen err] " + msg, KVpncEnum::error );


        if (ProcessMsg_connect.indexOf("Pluto is not running", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry("[ipsec whack listen " + i18n("Waiting for pluto"), KVpncEnum::debug);
            if (connectCounter > 25) {
                GlobalConfig->appendLogEntry("[ipsec whack listen " + i18n("Waiting for pluto needs too long"), KVpncEnum::debug);
                abort = true;
                IpsecGotError = true;
                IpsecWhackStatusTimer.stop();
            } else {
                // we have to give some time to sleep and try again...
                connect(IpsecWhackListenProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhacklisten()));
                connect(IpsecWhackListenProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhacklisten()));
                IpsecWhackListenProcess->terminate();
                sleep(2);
                if (IpsecWhackListenProcess->state() == QProcess::Running) {
                    IpsecWhackListenProcess->kill();
                    sleep(1);
                }
                connectCounter++;
                if ( !IpsecGotError)
                    ipsecStarted(0,QProcess::NormalExit);
            }
            return;
        }
        if (ProcessMsg_connect.indexOf("listening for IKE messages", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->KvpncDebugLevel > 3)
                GlobalConfig->appendLogEntry("[ipsec whack listen] " + i18n("Listen was successful."), KVpncEnum::debug);
            start_ipsec_initiate();
        } else {
            GlobalConfig->appendLogEntry("[ipsec whack listen err] " + ProcessMsg_connect, KVpncEnum::error);
        }

        if (abort) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("There is a reason to stop connecting, terminating \"%1\" process." , QString("ipsec whack --listen")) , KVpncEnum::debug);
            disconnectClicked();
            GlobalConfig->status = KVpncEnum::disconnected;
            setGuiStatus(KVpncEnum::disconnected);
            return ;
        }
    }
}

void KVpnc::readFromStdout_ipsecwhackstatus()
{
    if ( IpsecWhackStatusProcess ==0 || IpsecGotError )
        return;

    QStringList msg_list = QString(IpsecWhackStatusProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        if (GlobalConfig->KvpncDebugLevel > 5)
            GlobalConfig->appendLogEntry("[ipsec whack status] " + msg, KVpncEnum::debug);

        if (msg.indexOf(QString(GlobalConfig->currentProfile->getName()), 0, Qt::CaseInsensitive) > -1) {

            if (msg.indexOf("ISAKMP SA established", 0, Qt::CaseInsensitive) > -1  || msg.indexOf("transition from state STATE_QUICK_I1 to state STATE_QUICK_I2", 0, Qt::CaseInsensitive) > -1) {

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

                if (IpsecPhase2Up)
                    return;

                if (IpsecPhase1Up)
                    return;
                else
                    IpsecPhase1Up = true;



                if (GlobalConfig->KvpncDebugLevel > 1) {
                    if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan) {
                        GlobalConfig->appendLogEntry("[ipsec] " + i18n("IPSec phase 1 established."), KVpncEnum::info);
                    } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
                        GlobalConfig->appendLogEntry("[ipsec] " + i18n("Low level IPsec phase 1 established."), KVpncEnum::info);
                    }
                }
                if (GlobalConfig->currentProfile->getUseLeftSourceIp()) {
                    if ( GlobalConfig->KvpncDebugLevel > 3 )
                        GlobalConfig->appendLogEntry ( i18n ( "Adding virtual IP address" ), KVpncEnum::debug );
                    doAddRemoveVirtualIp("add");
                }
                doPingKickupTunnel();

            }

            else if (msg.indexOf("IPsec SA established", 0, Qt::CaseInsensitive) > -1) {
                ipsecPhase2Established();
            }
        }

//   // normal
//   if ( GlobalConfig->KvpncDebugLevel > 3 )
//   {
//    if ( NormalMsg )
        //    {
//      GlobalConfig->appendLogEntry ( "[ipsec whack status] " + msg, KVpncEnum::debug );
//     //   if (GlobalConfig->KvpncDebugLevel > 0)
//     //    GlobalConfig->appendLogEntry( "out: " + msg, KVpncEnum::debug );
//    }
        //    }
//   else if ( ErrorMsg )
        //      {
//    GlobalConfig->appendLogEntry ( "[ipsec whack status err] " + msg, KVpncEnum::error );
        //      }
        //
//   if ( abort )
        //       {
        //        if ( GlobalConfig->KvpncDebugLevel > 0 )
//     GlobalConfig->appendLogEntry ( i18n ( "There is a reason to stop connecting, terminating \"%1\" process.", QString( "ipsec whack status" )) , KVpncEnum::debug );
//    disconnectClicked();
//    GlobalConfig->status = KVpncEnum::disconnected;
//    setGuiStatus ( disconnected );
//    return ;
        //       }
    }
}

void KVpnc::readFromStderr_ipsecwhackstatus()
{
    QStringList msg_list = QString(IpsecWhackStatusProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        if (IpsecStatusCheck == true) {

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


            if (msg.indexOf("Pluto is not running", 0, Qt::CaseInsensitive) > -1) {
                GlobalConfig->appendLogEntry(i18n("ipsec daemon is not running, restarting it..."), KVpncEnum::info);
                startStopIpsec(true);
                sleep(1);
                startStopIpsec(false);
            }



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

            if (msg.indexOf("Pluto is not running", 0, Qt::CaseInsensitive) > -1) {
                if (!IpsecStartingInProgress) {
                    GlobalConfig->appendLogEntry(i18n("ipsec daemon is not running, restarting it..."), KVpncEnum::info);
                    startStopIpsec(true);
                    sleep(1);
                    startStopIpsec(false);
                }
            }
        }

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

void KVpnc::readFromStdout_ipsecwhackdelete()
{
    QStringList msg_list = QString(IpsecWhackDeleteProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

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

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

        if (abort) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("There is a reason to stop connecting, terminating \"%1\" process." , QString("ipsec whack --delete")) , KVpncEnum::debug);

            return ;
        }
    }
}

void KVpnc::readFromStderr_ipsecwhackdelete()
{
    bool abort = false;
    QStringList msg_list = QString(IpsecWhackDeleteProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);


        GlobalConfig->appendLogEntry("[ipsec whack delete err] " + msg, KVpncEnum::error);

        if (abort) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("There is a reason to stop connecting, terminating \"%1\" process.", QString("ipsec whack --delete")) , KVpncEnum::debug);

            return ;
        }
    }
}

void KVpnc::readFromStdout_tail_racoon()
{
    QStringList msg_list = QString(RacoonTailProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        bool abort = false;
        bool error_found = false;

        if (msg.indexOf("ERROR", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry("[racoon tail err] " + msg, KVpncEnum::error);
        } else {
            if (GlobalConfig->KvpncDebugLevel > 3) {
                if (msg.indexOf("ERROR", 0, Qt::CaseInsensitive) == -1)
                    GlobalConfig->appendLogEntry("[racoon tail] " + msg, KVpncEnum::debug);
            }
        }

//   // binding to port failed
//   if ( msg.indexOf ( "ERROR: failed to bind to address", 0, Qt::CaseInsensitive ) > -1  ||   msg.indexOf ( "ERROR: no address could be bound.", 0, Qt::CaseInsensitive ) > -1)
//   {
//
//    if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
//    {
//     if ( L2tpdProcess != 0 && L2tpdProcess->state() == QProcess::Running )
//      L2tpdProcess->kill();
//    }
//
//    QString NameAndPid = Utils ( GlobalConfig ).getNameAndPidOfProgramListen ( 500 );
//    GlobalConfig->appendLogEntry ( i18n ( "NameAndPid: %1" , QString(NameAndPid )) , KVpncEnum::debug );
//    int pid = -1;
//    QString Name = "";
//    if ( !NameAndPid.isEmpty() )
//    {
//     pid = NameAndPid.section ( '/', 0, 0 ).toInt();
//     Name = NameAndPid.section ( '/', 1, 1 );
//
//     if ( Name == "racoon" )
//     {
//
//      //RacoonProcess->setProcessChannelMode ( QProcess::MergedChannels );
// //      disconnect ( RacoonProcess, SIGNAL ( readyReadStandardOutput() ), this, SLOT ( readFromStdout_racoon() ) );
// //      disconnect ( RacoonProcess, SIGNAL ( readyReadStandardError() ), this, SLOT ( readFromStderr_racoon() ) );
//
//      if ( GlobalConfig->doKillRacoonIfStillRunning && abort == false )
//      {
//       if ( GlobalConfig->KvpncDebugLevel > 3 )
//        GlobalConfig->appendLogEntry ( i18n ( "%1 could not bind to port, trying to kill it...." , QString( "racoon" )) , KVpncEnum::error );
//
//       QProcess killracoonprocess ( this );
//       QString proc = GlobalConfig->pathToKillall;
//       QStringList args;
//       args.append( "racoon" );
//       killracoonprocess.setEnvironment(*env);
//       killracoonprocess.start(proc,args);
//       if ( !killracoonprocess.waitForStarted() )
//       {
//        GlobalConfig->appendLogEntry ( i18n ( "%1 could not be killed.", QString("racoon" )) , KVpncEnum::error );
//        GlobalConfig->appendLogEntry ( QString ( "[racoon err] " + i18n ( "Bind to given port has been failed. Another %1 process is running. Please stop %1 first." , QString( "racoon" ) )) , KVpncEnum::error );
        //abort = true;
//       }
//       else
//       {
//        killracoonprocess.waitForFinished();
//         usleep ( 500 );
//
//        sleep ( 2 );
//
//        // restart racoon
//        //       if ( RacoonProcess != 0)
//        //        RacoonProcess->kill();
//
//
//        putenv ( ( char* ) ( "LC_ALL=C" ) );
//        RacoonProcess = new QProcess( this );
//    QString proc = GlobalConfig->pathToRacoon;
//    QStringList args;
//        /*args.append ( "-F" )*/; // foreground we want :)
// //        args.append ( "-v" );
//        args.append( "-f" );
//        args.append ( tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".conf" );
// //        args.append ( "-l" ); // logfile (we get content with tail process)
// //        args.append ( tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log" );
//        if ( GlobalConfig->KvpncDebugLevel > 0 )
//         GlobalConfig->appendLogEntry ( "racoon: " + GlobalConfig->pathToRacoon + " -f " + tmpPath + "/racoon" + GlobalConfig->currentProfile->getName() + ".conf", KVpncEnum::debug );
//
//
//         //RacoonProcess->setProcessChannelMode(QProcess::MergedChannels );
// //        connect ( RacoonProcess, SIGNAL ( readyReadStandardOutput() ), this, SLOT ( readFromStdout_racoon() ) );
// //        connect ( RacoonProcess, SIGNAL ( readyReadStandardError() ), this, SLOT ( readFromStderr_racoon() ) );
//
//    RacoonProcess->setEnvironment(*env);
//    RacoonProcess->start(proc,args);
//        if ( !RacoonProcess->waitForStarted() )
//        {
//         if ( GlobalConfig->KvpncDebugLevel > 0 )
//          GlobalConfig->appendLogEntry ( i18n ( "Failed to start \"%1\"." , QString( "racoon" )), KVpncEnum::error );
//
//         GlobalConfig->appendLogEntry ( QString ( "[racoon err] " + i18n ( "Bind to given port has been failed. Another %1 process is running. Please stop %1 first." , QString("racoon" ) ) , KVpncEnum::error );
//         abort = false;
//        }
//        else
//        {
//         if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
//         {
//          start_l2tpd();
//          if ( GlobalConfig->KvpncDebugLevel > 0 )
//           GlobalConfig->appendLogEntry ( i18n ( "%1 was already running. %2 and %3 are killed and restarted." , QString("racoon" ),QString( "racoon") , QString("l2tpd" )), KVpncEnum::debug );
//         }
//         else
//         {
//          doTailRacoonLog();
//          racoonStarted();
//          if ( GlobalConfig->KvpncDebugLevel > 0 )
//           GlobalConfig->appendLogEntry ( i18n ( "%1 was already running. It was killed and restarted." , QString( "racoon" )), KVpncEnum::debug );
//         }
//        }
//       }
//      }
//      else
//      {
//       KMessageBox::error ( this, i18n ( "Binding port %1 failed. Program \"%2\" with PID \"%3\" is using it. You have to stop it first.", QString(QString().setNum ( 500 ) ), Name , QString().setNum ( pid ) ) );
//       GlobalConfig->appendLogEntry ( i18n ( "Port binding failed" ) , KVpncEnum::error );
//       abort = true;
//      }
//     }
//     else
//     {
//      KMessageBox::error ( this, i18n ( "Binding port %1 failed. Program \"%2\" with PID \"%3\" is using it. You have to stop it first." , QString(QString().setNum ( 500 ) ),  Name , QString().setNum ( pid ) ) );
//      abort = true;
//     }
//    }
//    else
//    {
//     KMessageBox::error ( this, i18n ( "Port binding failed" ) );
//     GlobalConfig->appendLogEntry ( i18n ( "Port binding failed" ) , KVpncEnum::error );
//     abort = true;
//    }
//
//   }

        if (msg.indexOf("ERROR: failed to bind to address", 0, Qt::CaseInsensitive) > -1  ||   msg.indexOf("ERROR: no address could be bound.", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry(i18n("Port binding failed") , KVpncEnum::error);
            abort = true;
        }

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

            abort = true;
        } else if (msg.indexOf("ERROR: failed to process packet.", 0, Qt::CaseInsensitive) > -1) {
            //   KMessageBox::error( this, i18n( "failed to process packet" ) );
            GlobalConfig->appendLogEntry(i18n("failed to process packet") , KVpncEnum::error);

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

            abort = true;
        } else if (msg.indexOf("ERROR: delete phase1 handle.", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Phase 1 negotiation of IPSec connection has failed. Please check encryption of phase 1 and hash algorithm."));
            GlobalConfig->appendLogEntry(i18n("Phase 1 negotiation of IPSec connection has failed. Please check encryption of phase 1 and hash algorithm.") , KVpncEnum::error);

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

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

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

            abort = true;
        } else if (msg.indexOf("ERROR: the peer's certificate is not verified", 0, Qt::CaseInsensitive) > -1) {
            //    KMessageBox::error( this, i18n( "ERROR: the peer's certificate is not verified" ) );
            GlobalConfig->appendLogEntry(i18n("ERROR: the peer's certificate is not verified") , KVpncEnum::error);

            abort = true;
        } else if (msg.indexOf("ERROR: no configuration found for", 0, Qt::CaseInsensitive) > -1) {
            //    KMessageBox::error( this, i18n( "ERROR: no configuration found" ) );
            GlobalConfig->appendLogEntry(i18n("ERROR: no configuration found") , KVpncEnum::error);

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

            abort = true;
        } else if (msg.indexOf("ERROR: failed to get subjectAltName", 0, Qt::CaseInsensitive) > -1) {
            //    KMessageBox::error( this, i18n( "ERROR: failed to get subjectAltName" ) );
            GlobalConfig->appendLogEntry(i18n("ERROR: failed to get subjectAltName") , KVpncEnum::error);

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

            abort = true;
        } else if (msg.indexOf( "ERROR: fatal INVALID-ID-INFORMATION", 0 , Qt::CaseInsensitive ) > -1 ) {
            KMessageBox::error ( this, i18n ( "Peer refused ID settings. Please verify the local ID in racoon and remote network in Network - General settings." ) );
            GlobalConfig->appendLogEntry ( i18n ( "Peer refused ID settings. Please verify the local ID in racoon and remote network in Network - General settings." ) , KVpncEnum::error );
            abort = true;
        } else if ( msg.indexOf("STATE: phase1 up", 0 , Qt::CaseInsensitive ) > -1  ||  msg.indexOf("ISAKMP-SA established", 0 , Qt::CaseInsensitive ) > -1 ) {
            if ( GlobalConfig->KvpncDebugLevel > 1 ) {
                if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon )
                {
                    GlobalConfig->appendLogEntry ( "[racoon] " + i18n ( "IPSec phase 1 established." ), KVpncEnum::info );
                }
                else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon )
                {
                    GlobalConfig->appendLogEntry ( "[racoon] " + i18n ( "Low level IPsec phase 1 established." ), KVpncEnum::info );
                }
            }
            if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon && GlobalConfig->currentProfile->getUseLeftSourceIp()) {
                if ( GlobalConfig->KvpncDebugLevel > 3 )
                    GlobalConfig->appendLogEntry ( i18n ( "Adding virtual IP address" ), KVpncEnum::debug );
                doAddRemoveVirtualIp("add");
            }
            doPingKickupTunnel();
        } else if ( msg.indexOf("STATE: phase1 down", 0 , Qt::CaseInsensitive ) > -1 ) {
            KMessageBox::error ( this, i18n ( "Phase 1 negotiation failed due to time up." ) );
            GlobalConfig->appendLogEntry ( i18n ( "ERROR: phase1 negotiation failed due to time up." ) , KVpncEnum::error );
            abort = true;
        } else if (msg.indexOf("IPsec-SA established", 0, Qt::CaseInsensitive) > -1 || msg.indexOf("STATE: upscript finished", 0, Qt::CaseInsensitive) > -1) {
            racoon_tunnel_state++;
            if (racoon_tunnel_state  == 1) {
                if (GlobalConfig->KvpncDebugLevel > 1)
                    GlobalConfig->appendLogEntry("[racoon tail] " + i18n("First tunnel is now up, waiting for second one..."), KVpncEnum::debug);
            } else if ( racoon_tunnel_state == 2 ) {

                if (GlobalConfig->currentProfile->getUseModeConfig()) {
                    QFile ModeCfgFile(QString(tmpPath + "/racoon-" + GlobalConfig->currentProfile->getName() + ".modecfg"));
                    if (ModeCfgFile.exists()) {
                        QString TmpDns1 = "";
                        QString TmpDns2 = "";
                        QString internal_addr4 = "";
                        QString internal_netmask4 = "";
                        QString internal_cidr4 = "";
                        QString internal_dns4 = "";
                        QString internal_dns4_list = "";
                        QString internal_wins4 = "";
                        QString internal_wins4_list = "";
                        QString split_include = "";
                        QString split_local = "";
                        QString default_domain = "";
                        QString resolvtemp = "";
                        if (ModeCfgFile.open(QIODevice::ReadOnly)) {
                            QStringList contentlist = QString(ModeCfgFile.readAll()).split("\n");
                            for (int i = 0; i < contentlist.size(); ++i) {
                                QString line = contentlist.at(i);
                                if (GlobalConfig->KvpncDebugLevel > 5)
                                    GlobalConfig->appendLogEntry("[ModeCfg] " + line, KVpncEnum::debug);

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

                        // tmp
                        TmpDns1 = internal_dns4;


                        QFile racoonupfile(tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".up");
                        QTextStream racoonupstream(&racoonupfile);
                        if (racoonupfile.open(QIODevice::WriteOnly)) {
                            QString DefaultDevice = NetworkInterface(GlobalConfig, parent).getDefaultInterface();
                            /* update dns? */
                            if (GlobalConfig->currentProfile->getUseDnsUpdate()) {
                                racoonupstream << "if [ -x /sbin/resolvconf ] ; then\n";
                                racoonupstream << " dev=$1\n";
                                racoonupstream << " if [ -z $dev ] ; then\n";
                                racoonupstream << "  dev=\"" + DefaultDevice + "\"\n";
                                racoonupstream << "fi\n";
                                bool no_nameserver=true;
                                if (!TmpDns1.isEmpty() || !TmpDns2.isEmpty()) {
                                    no_nameserver = false;
                                    racoonupstream << "if [ -x /sbin/resolvconf ] ; then\n";
                                    if (TmpDns2.isEmpty()) {
                                        racoonupstream << "echo \"nameserver " << TmpDns1 << "\"" << " " << "$dev\" > " + tmpPath + "+resolvconf." + GlobalConfig->currentProfile->getName() + "\n";
                                    } else {
                                        racoonupstream << "echo \"nameserver " << TmpDns1 << "\"\nnameserver " << TmpDns2 << " " << "$dev\" > " + tmpPath + "+resolvconf." + GlobalConfig->currentProfile->getName() + "\n";
                                    }
                                    if (no_nameserver == true) {
                                        racoonupstream << "  cat   " + tmpPath + "/resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() + " | grep nameserver >> " + tmpPath + "+resolvconf." + GlobalConfig->currentProfile->getName() + "\n";
                                    }
                                    racoonupstream << " cat   " + tmpPath + "+resolvconf." + GlobalConfig->currentProfile->getName()+ " | /sbin/resolvconf -a $dev\n";

                                    racoonupstream << "else" << "\n";
                                    racoonupstream << "  echo >> /etc/resolv.conf\n";
                                    racoonupstream << "  echo \"# generated by kvpnc. Do not edit it.\" > /etc/resolv.conf" << "\n";
                                    racoonupstream << "  echo \"# profile: " + GlobalConfig->currentProfile->getName() << "\" >> /etc/resolv.conf" << "\n";
                                    racoonupstream << "  echo \"nameserver " << TmpDns1 << "\" >> /etc/resolv.conf" << "\n";
                                    if (!TmpDns2.isEmpty())
                                        racoonupstream << "  echo \"nameserver " << TmpDns2 << "\" >> /etc/resolv.conf" << "\n";
                                    if (no_nameserver == true) {
                                        racoonupstream << "  cat " << tmpPath + "/resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() + " | grep nameserver >> /etc/resolv.conf\n";
                                    }
                                    racoonupstream << "fi" << "\n";

                                }

                                QProcess pppdUpProcess(this);
                                QString proc = GlobalConfig->InterpreterShell;
                                QStringList args;
                                args.append(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".up");
                                pppdUpProcess.setEnvironment(*env);
                                pppdUpProcess.start(proc, args);
                                if (!pppdUpProcess.waitForStarted()) {
                                    KMessageBox::sorry(this, i18n("\"%1\" (%2) start failed." , QString("PppdUpScript"), QString(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".up")));
                                } else {
                                    if (GlobalConfig->KvpncDebugLevel > 0)
                                        GlobalConfig->appendLogEntry(i18n("\"%1\" (%2) started." , QString("PppdUpScript"), QString(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".up")) , KVpncEnum::debug);
                                    waitForFinished(&pppdUpProcess, 100);


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

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

                    }
                }


                doIptablesRacoon();
                addRouteRacoon();

                if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon) {
                    if ( GlobalConfig->KvpncDebugLevel > 1 ) {
                        GlobalConfig->appendLogEntry ( "[racoon tail] " + i18n ( "IPSec phase 2 established." ), KVpncEnum::info );
                    }
                    GlobalConfig->appendLogEntry("[racoon tail] " + i18n("Connection established."), KVpncEnum::success);

                    sec = hour = min = 0;

                    GlobalConfig->status = KVpncEnum::connected;

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


                    doIptablesRacoon();
                    addRouteRacoon();

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

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

                    if (GlobalConfig->currentProfile->getUseConnectionStatusCheck()) {
                        startConnectionStatusCheck();
                    }
                }
                if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon) {
                    GlobalConfig->appendLogEntry("[racoon tail] " + i18n("Low level IPsec connection established."), KVpncEnum::success);
                    start_l2tpd();
                }

            }
        } else if ( msg.indexOf("ISAKMP-SA expired", 0 , Qt::CaseInsensitive ) > -1 ) {
            if ( GlobalConfig->KvpncDebugLevel > 3 )
                GlobalConfig->appendLogEntry ( i18n ( "Phase1 expired" ) , KVpncEnum::debug );
            abort = false;
        } else if (msg.indexOf("Reading configuration from", 0, Qt::CaseInsensitive) > -1) {
//    GlobalConfig->appendLogEntry ( i18n ( "Reading configuration from got" ) , KVpncEnum::debug );
//    sleep(3);
//       racoonStarted();
        } else if (msg.indexOf("ERROR: none message must be encrypted", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Phase 1 negotiation of IPSec connection has failed. Please check encryption of phase 1 and hash algorithm."));
            GlobalConfig->appendLogEntry(i18n("Phase 1 negotiation of IPSec connection has failed. Please check encryption of phase 1 and hash algorithm.") , KVpncEnum::error);
            abort = true;
        } else if ( msg.indexOf("ERROR: fatal NO-PROPOSAL-CHOSEN", 0 , Qt::CaseInsensitive ) > -1 ) {
            if (!error_found)
                KMessageBox::error ( this, i18n ( "Wrong connection parameters used. Please verify the connection settings." ) );
            GlobalConfig->appendLogEntry ( i18n ( "Peer reported that we use wrong connection parameters." ), KVpncEnum::error );
            abort = true;
        } else if ( msg.indexOf("ERROR: phase1 negotiation failed due to time up.", 0 , Qt::CaseInsensitive ) > -1 ) {
            if (!error_found)
                KMessageBox::error ( this, i18n ( "Phase1 negotiation failed due to time up." ) );
            GlobalConfig->appendLogEntry ( i18n ( "ERROR: phase1 negotiation failed due to time up." ), KVpncEnum::error );
            abort = true;
        }



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

    }
}

void KVpnc::readFromStderr_tail_racoon()
{
    bool error_found =false;
    bool abort = false;
    QStringList msg_list = QString(RacoonTailProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        //  if ( GlobalConfig->KvpncDebugLevel > 0 ) {
        GlobalConfig->appendLogEntry("[racoon tail err] " + msg, KVpncEnum::error);
        //}
        if ( msg.indexOf("ERROR: phase1 negotiation failed due to time up.", 0 , Qt::CaseInsensitive ) > -1 ) {
            if (!error_found)
                KMessageBox::error ( this, i18n ( "Phase1 negotiation failed due to time up." ) );
            GlobalConfig->appendLogEntry ( i18n ( "ERROR: phase1 negotiation failed due to time up." ) , KVpncEnum::error );
            abort = true;
        }
        if ( abort )
        {
            GlobalConfig->appendLogEntry ( i18n ( "There is a reason for stop connecting, terminating \"%1\" process.", QString("racoon") ) , KVpncEnum::error );
            disconnectClicked();
        }

    }
}

void KVpnc::readFromStdout_racoonctl()
{
    QStringList msg_list = QString(RacoonctlProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        bool abort = false;
        //   if ( GlobalConfig->KvpncDebugLevel > 3 )
        {
            GlobalConfig->appendLogEntry("[racoonctl] " + msg, KVpncEnum::debug);
        }
        if (msg.indexOf("ERROR", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry("[racoonctl err] " + msg, KVpncEnum::error);
        }
        if (msg.indexOf("send: Bad file descriptor", 0, Qt::CaseInsensitive) > -1) {

            //    KMessageBox::error ( this, i18n ( "Racoon seems to be not running." )  );
            GlobalConfig->appendLogEntry(i18n("Racoon seems to be not running.")  , KVpncEnum::error);

            //    if (GlobalConfig->KvpncDebugLevel > 3)
            //     GlobalConfig->appendLogEntry ( i18n ( "Racoon seems to be not running." )  , KVpncEnum::debug );

            //    if (RacoonctlConnectCounter > 25)
            //    {
            //     GlobalConfig->appendLogEntry ( "[racoonctl] " + i18n("Waiting for racoon needs too long"), KVpncEnum::debug );
            //     abort=true;
            //    }
            //    else
            //    {
            //
            //     if (GlobalConfig->KvpncDebugLevel > 3)
            //      GlobalConfig->appendLogEntry ( i18n ( "Racoon seems to be not running, waiting." )  , KVpncEnum::debug );
            //
            //     // we have to give some time to sleep and try again...
            //     RacoonctlProcess->tryTerminate();
            //     sleep(2);
            //     if (RacoonctlProcess->state() == QProcess::Running)
            //     {
            //      disconnect( RacoonctlProcess, SIGNAL( readyReadStandardOutput() ), this, SLOT( readFromStdout_racoonctl() ) );
            //      disconnect( RacoonctlProcess, SIGNAL( readyReadStandardError() ), this, SLOT( readFromStderr_racoonctl() ) );
            //      disconnect ( RacoonctlProcess, SIGNAL ( finished ( int, QProcess::ExitStatus )), this, SLOT(racoonctlExited(int, QProcess::ExitStatus)) ) );
            //      RacoonctlProcess->kill();
            //      sleep(1);
            //      racoonStarted();
            //     }
            //     RacoonctlConnectCounter++;
            //    }

            //    abort =true;
        } else if (msg.indexOf("racoonctl: Cannot send combuf", 0, Qt::CaseInsensitive) > -1) {
            //KMessageBox::error ( this, i18n ( "racoonctl: Cannot send combuf" )  );
            GlobalConfig->appendLogEntry(i18n("racoonctl: Cannot send combuf")  , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("Error: Peer not responding", 0, Qt::CaseInsensitive) > -1) {
            //KMessageBox::error ( this, i18n ( "racoonctl: Peer not responding" )  );
            GlobalConfig->appendLogEntry(i18n("racoonctl: Peer not responding")  , KVpncEnum::error);
            abort = true;
        }
        if (msg.indexOf("Password:", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->VpncDebugLevel > 0)
                GlobalConfig->appendLogEntry("[racoonctl] " + i18n("User password requested, send it...\n"), KVpncEnum::debug);

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

            if (GlobalConfig->KvpncDebugLevel > 8)
                GlobalConfig->appendLogEntry("[racoonctl] " + i18n("User password: %1\n" , QString(UserPassStr)), KVpncEnum::debug);


            RacoonctlProcess->write(UserPassStr.toUtf8());
            RacoonctlProcess->write("\n");
        } else if (msg.indexOf("VPN connexion terminated", 0, Qt::CaseInsensitive) > -1) {
            //KMessageBox::error ( this, i18n ( "VPN connexion terminated" )  );
            GlobalConfig->appendLogEntry(i18n("VPN connexion terminated")  , KVpncEnum::debug);
            abort = false;
        } else if (msg.indexOf("VPN connexion established", 0, Qt::CaseInsensitive) > -1) {
            // this is useless because it reports phase 1 only.
//             if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon) {
//                 GlobalConfig->appendLogEntry("[racoon] " + i18n("Low level connection established."), KVpncEnum::success);
//                 racoon_tunnel_state = 1;
//                 start_l2tpd();
//             } else {
//                 GlobalConfig->appendLogEntry("[racoon] " + i18n("Connection established."), KVpncEnum::success);
//
//                 sec = hour = min = 0;
//
//                 GlobalConfig->status = KVpncEnum::connected;
//
//                 connect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));
//                 durationTimer.start(1000);
//                 setGuiStatus(KVpncEnum::connected);
//
//                 setFirewallAfterConnect();
//                 if (GlobalConfig->currentProfile->getExecuteCmdAfterConnect())
//                     executeCommandAfterConnect();
//
//                 if (GlobalConfig->currentProfile->getUseAdditionalNetworkRoutes() && !GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty())
//                     addAdditionalNetworkRoutes();
//
//                 if (GlobalConfig->currentProfile->getUseConnectionStatusCheck()) {
//                     startConnectionStatusCheck();
//                 }
//             }
        }
        if (abort) {
            GlobalConfig->appendLogEntry(i18n("There is a reason to stop connecting, terminating \"%1\" process." , QString("racoon")) , KVpncEnum::error);
            disconnectClicked();
        }
    }
}

void KVpnc::readFromStderr_racoonctl()
{
    QStringList msg_list = QString(RacoonctlProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        bool abort = false;

        //  if ( GlobalConfig->KvpncDebugLevel > 0 )
        GlobalConfig->appendLogEntry("[racoonctl err] " + msg, KVpncEnum::error);

        if (msg.indexOf("send: Bad file descriptor", 0, Qt::CaseInsensitive) > -1) {
//    KMessageBox::error ( this, i18n ( "Racoon seems to be not running." )  );
            GlobalConfig->appendLogEntry(i18n("Racoon seems to be not running.")  , KVpncEnum::error);
//    abort =true;
        } else if (msg.indexOf("racoonctl: Cannot send combuf", 0, Qt::CaseInsensitive) > -1) {
//    KMessageBox::error ( this, i18n ( "racoonctl: Cannot send combuf" )  );
            GlobalConfig->appendLogEntry(i18n("racoonctl: Cannot send combuf")  , KVpncEnum::error);
//    abort =true;
        }
        if (msg.indexOf("Password:", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->VpncDebugLevel > 0)
                GlobalConfig->appendLogEntry("[racoonctl err] " + i18n("User password requested, send it...\n"), KVpncEnum::debug);

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

            if (GlobalConfig->KvpncDebugLevel > 8)
                GlobalConfig->appendLogEntry("[racoonctl err] " + i18n("User password: %1\n"  , QString(UserPassStr)), KVpncEnum::debug);


            RacoonctlProcess->write(UserPassStr.toUtf8());
            RacoonctlProcess->write("\n");
        }


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

void KVpnc::readFromStdout_pptp()
{
    QStringList msg_list = QString(PptpProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        if ( !msg.isEmpty() && GlobalConfig->KvpncDebugLevel > 4 )
        {
            GlobalConfig->appendLogEntry ( "[pptp raw]: "+msg, KVpncEnum::debug );
        }


        bool abort = false;
        bool connectSuccess = false;
        bool allowReconnect = false;

        if (msg.indexOf("could not find module", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Module not found."));
            GlobalConfig->appendLogEntry(i18n("Module not found.") , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("Connection terminated.", 0, Qt::CaseInsensitive) > -1) {
            //KMessageBox::error( this, i18n( "Connection has been terminated." ) );
            GlobalConfig->appendLogEntry(i18n("Connection has been terminated."), KVpncEnum::info);
            abort = true;
            allowReconnect = true;
        } else if (msg.indexOf("Modem hangup", 0, Qt::CaseInsensitive) > -1 || msg.indexOf("Modem hung up", 0, Qt::CaseInsensitive) > -1) {
            if (!GlobalConfig->currentProfile->getDoReconnectAfterConnectionLost())
                KMessageBox::error(this, i18n("Remote modem has hung up. Connection was terminated."));
            GlobalConfig->appendLogEntry(i18n("Remote modem has hung up. Connection was terminated.") , KVpncEnum::error);
            abort = true;
            allowReconnect = true;
        } else if (msg.indexOf("No route to host", 0, Qt::CaseInsensitive) > -1) {
            if (!GlobalConfig->currentProfile->getDoReconnectAfterConnectionLost())
                KMessageBox::error(this, i18n("No route to host."));
            GlobalConfig->appendLogEntry(i18n("No route to host."), KVpncEnum::error);
            abort = true;
            allowReconnect = true;
        } else if (msg.indexOf("authentication failed", 0, Qt::CaseInsensitive) > -1) {
            timer.stop();
            connectCounter = 0;
//    disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
            KMessageBox::error(this, i18n("Authentication has failed."));
            GlobalConfig->appendLogEntry(i18n("Authentication has failed.") , KVpncEnum::error);
            //abort = true;
            AuthRetry = true;
            GlobalConfig->haveUserData = false;
            disconnectClicked();
// 			while(GlobalConfig->status != KVpncEnum::disconnected) {
// 				usleep(500);
// 				if (GlobalConfig->appPointer->hasPendingEvents())
// 					GlobalConfig->appPointer->processEvents();
// 			}
            connectClicked();
// 			return;
        } else if (msg.indexOf("peer refused to authenticate", 0, Qt::CaseInsensitive) > -1) {
            timer.stop();
            connectCounter = 0;
//    disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
            if (!GlobalConfig->currentProfile->getDoReconnectAfterConnectionLost())
                KMessageBox::error(this, i18n("The peer refused to authenticate."));
            GlobalConfig->appendLogEntry(i18n("The peer refused to authenticate.") , KVpncEnum::error);
            abort = true;
            //abort = true;
            AuthRetry = true;
            GlobalConfig->haveUserData = false;
            disconnectClicked();
// 			while(GlobalConfig->status != KVpncEnum::disconnected) {
// 				usleep(500);
// 				if (GlobalConfig->appPointer->hasPendingEvents())
// 					GlobalConfig->appPointer->processEvents();
// 			}
            connectClicked();
            return;
        } else if (msg.indexOf("EAP: peer reports authentication failure", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("The peer refused to authenticate (it wants EAP). Please check username, password and EAP settings."));
            GlobalConfig->appendLogEntry(i18n("The peer refused to authenticate (it wants EAP). Please check username, password and EAP settings.") , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("MPPE required but peer negotiation failed", 0, Qt::CaseInsensitive) > -1) {
            timer.stop();
            connectCounter=0;
            // 			disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
            KMessageBox::error ( this, i18n ( "The peer refused to use MPPE encryption. Maybe you have to disable MPPE encryption." ) );
            GlobalConfig->appendLogEntry ( i18n ( "The peer refused to use MPPE encryption. Maybe you have to disable MPPE encryption." ) , KVpncEnum::error );
            abort = true;
            GlobalConfig->haveUserData = false;
        } else if (msg.indexOf("Call manager exited with error", 0, Qt::CaseInsensitive) > -1) {
            //KMessageBox::error( this, i18n( "Call manager exited with a error." ) );
            GlobalConfig->appendLogEntry(i18n("Call manager exited with error.") , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("connect: Connection timed out", 0, Qt::CaseInsensitive) > -1) {
            //KMessageBox::error( this, i18n( "connect: Connection timed out" ) );
            GlobalConfig->appendLogEntry(i18n("connect: Connection timed out") , KVpncEnum::error);
            abort = true;
            allowReconnect = true;
        } else if (msg.indexOf("Input/output error", 0, Qt::CaseInsensitive) > -1) {
            if ( !GlobalConfig->currentProfile->getDoReconnectAfterConnectionLost() )
                KMessageBox::error( this, i18n( "Input/output error" ) );
            GlobalConfig->appendLogEntry(i18n("Input/output error") , KVpncEnum::error);
            abort = true;
            allowReconnect = true;
        } else if (msg.indexOf("Using interface", 0, Qt::CaseInsensitive) > -1) {
            PppdDevice = msg.right(msg.length() - 16);
            if (GlobalConfig->PppdDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Tunnel device: %1\n"  , QString(PppdDevice)), KVpncEnum::debug);
            GlobalConfig->currentProfile->setNetworkDevice(PppdDevice);
            //
            //
            //   NetworkInterface iface(GlobalConfig,parent);
            //   TunnelInterfaceIP = iface.getInterfaceIP( PppdDevice );
            //   if (GlobalConfig->VpncDebugLevel > 0 )
            //    GlobalConfig->appendLogEntry( "[pppd] "+i18n( "Tunnel IP:" , QString(TunnelInterfaceIP)) , KVpncEnum::debug);
            //

            abort = false;
        } else if (msg.indexOf("tcflush failed: Bad file descriptor", 0, Qt::CaseInsensitive) > -1) {
            if ( !GlobalConfig->currentProfile->getDoReconnectAfterConnectionLost() )
                KMessageBox::error(this, i18n("Sending data has failed. Connection was terminated."));
            GlobalConfig->appendLogEntry(i18n("Sending data has failed. Connection was terminated.") , KVpncEnum::error);
            abort = true;
            allowReconnect = true;
        } else if (msg.indexOf("Modem hangup", 0, Qt::CaseInsensitive) > -1) {
            if (!GlobalConfig->currentProfile->getDoReconnectAfterConnectionLost())
                KMessageBox::error(this, i18n("Remote modem has hung up. Connection was terminated."));
            GlobalConfig->appendLogEntry(i18n("Remote modem has hung up. Connection was terminated.") , KVpncEnum::error);
            abort = true;
            allowReconnect = true;
        } else if (msg.indexOf("connect: Connection refused", 0, Qt::CaseInsensitive) > -1) {
            if (!GlobalConfig->currentProfile->getDoReconnectAfterConnectionLost())
                KMessageBox::error(this, i18n("Connection has been refused. Terminate."));
            GlobalConfig->appendLogEntry(i18n("Connection has been refused. Terminate.") , KVpncEnum::error);
            abort = true;
            allowReconnect = true;
        } else if (msg.indexOf("primary DNS address", 0, Qt::CaseInsensitive) > -1) {
            // example: primary DNS address 132.210.*.2 secondary DNS address 132.210.**.2
            bool got2dns = false;
            QString DNS1 = msg.section(' ', 3, 3);
            QString DNS2 = msg.section(' ', 7, 7);

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

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

            if (GlobalConfig->KvpncDebugLevel > 0) {
                if (got2dns)
                    GlobalConfig->appendLogEntry(i18n("Got DNS1: %1, DNS2: %2"  , QString(DNS1), DNS2) , KVpncEnum::debug);
                else
                    GlobalConfig->appendLogEntry(i18n("Got DNS1: %1"  , QString(DNS1)) , KVpncEnum::debug);
            }
            abort = false;
        } else if (msg.indexOf("CHAP authentication succeeded", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("CHAP authentication succeeded.\n"), KVpncEnum::debug);
            abort = false;
        } else if (msg.indexOf("MPPE 128-bit stateless compression enabled", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("MPPE 128-bit stateless compression enabled.\n"), KVpncEnum::debug);
            abort = false;
        } else if (msg.indexOf("local", 0, Qt::CaseInsensitive) > -1) {
            //    if (GlobalConfig->KvpncDebugLevel > 0)
//       GlobalConfig->appendLogEntry ( i18n( "adr: %1\n"  , QString(msg)), KVpncEnum::debug);
            TunnelInterfaceIP = msg.simplified().section(' ', 3, 3);
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Tunnel IP address: %1\n"  , QString(TunnelInterfaceIP)), KVpncEnum::debug);
            abort = false;
        } else if (msg.indexOf("Loopback detected", 0, Qt::CaseInsensitive) > -1) {
//    KMessageBox::error ( this, i18n ( "Loopback detected. Reconnecting." ) );
            GlobalConfig->appendLogEntry(i18n("Loopback detected. Reconnecting.") , KVpncEnum::error);
            abort = true;
            connectClicked();
        } else if (msg.indexOf("remote IP address", 0, Qt::CaseInsensitive) > -1)
            connectSuccess = true;

        if (abort) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("There is a reason to stop connecting, terminating \"%1\" process." , QString("pppd")) , KVpncEnum::debug);
            disconnectClicked();
// 			while(GlobalConfig->status != KVpncEnum::disconnected) {
// 				usleep(500);
// 				if (GlobalConfig->appPointer->hasPendingEvents())
// 					GlobalConfig->appPointer->processEvents();
// 			}
            GlobalConfig->status = KVpncEnum::disconnected;
            setGuiStatus(KVpncEnum::disconnected);

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

                  if ( kvpnc_start_marker_found == false )
                  {
                   chapsecret_content += line;
                   chapsecret_content += '\n';
                  }
                 }
                 ChapSecretsFile.close();
                 if ( ChapSecretsFile.remove() )
                 {
                  if ( GlobalConfig->KvpncDebugLevel > 2 )
                   GlobalConfig->appendLogEntry ( i18n ( "File %1 successfully removed"  , QString("/etc/ppp/chap-secrets" )), KVpncEnum::debug );
                  //        ChapSecretsFile.setName("/etc/ppp/chap-secrets2");
                  if ( ChapSecretsFile.open ( QIODevice::WriteOnly ) )
                  {
                   stream.setDevice ( &ChapSecretsFile );
                   stream << chapsecret_content;
                   ChapSecretsFile.close();
                   if ( GlobalConfig->KvpncDebugLevel > 2 )
                    GlobalConfig->appendLogEntry ( i18n ( "File %1 successfully rewritten"  , QString("/etc/ppp/chap-secrets" )), KVpncEnum::debug );
                  }
                  else
                  {
                   if ( GlobalConfig->KvpncDebugLevel > 2 )
                    GlobalConfig->appendLogEntry ( i18n ( "File %1 rewrite failed"  , QString("/etc/ppp/chap-secrets" )), KVpncEnum::error );
                  }
                 }
                 else
                 {
                  if ( GlobalConfig->KvpncDebugLevel > 2 )
                   GlobalConfig->appendLogEntry ( i18n ( "File %1 remove failed"  , QString("/etc/ppp/chap-secrets" )), KVpncEnum::error );
                 }

                }
                else
                {
                 GlobalConfig->appendLogEntry ( i18n ( "File %1 could not be opened."  , QString("/etc/ppp/chap-secrets" )), KVpncEnum::error );
                }
               }
               if (GlobalConfig->currentProfile->getAuthMethod() == "pap")
               {
                // remove kvpnc entries from pap-secerets
                QFile papSecretsFile ( "/etc/ppp/pap-secrets" );
                if ( GlobalConfig->KvpncDebugLevel > 0 )
                 GlobalConfig->appendLogEntry ( i18n ( "pppd secrets file: %1", QString("/etc/ppp/chap-secrets" )), KVpncEnum::debug );
                QTextStream stream ( &papSecretsFile );
                if ( papSecretsFile.open ( QIODevice::ReadOnly ) )
                {
                 QString line = "";
                 QString papsecret_content = "";
                 bool kvpnc_start_marker_found = false;
                 bool kvpnc_end_marker_found = false;
                 while ( !stream.atEnd() )
                 {
                  line = stream.readLine(); // line of text excluding '\n'
                  if ( line == "# --- generated by kvpnc. Do not edit it." )
                  {
                   kvpnc_end_marker_found = true;
                   if ( GlobalConfig->KvpncDebugLevel > 2 )
                    GlobalConfig->appendLogEntry ( i18n ( "End marker in %1 found"  , QString("/etc/ppp/pap-secrets" )), KVpncEnum::debug );
                  }
                  if ( line == "# +++ generated by kvpnc. Do not edit it." )
                  {
                   kvpnc_start_marker_found = true;
                   if ( GlobalConfig->KvpncDebugLevel > 2 )
                    GlobalConfig->appendLogEntry ( i18n ( "Start marker in %1 found"  , QString("/etc/ppp/pap-secrets" )), KVpncEnum::debug );
                  }

                  if ( kvpnc_start_marker_found == false )
                  {
                   papsecret_content += line;
                   papsecret_content += '\n';
                  }
                 }
                 papSecretsFile.close();
                 if ( papSecretsFile.remove() )
                 {
                  if ( GlobalConfig->KvpncDebugLevel > 2 )
                   GlobalConfig->appendLogEntry ( i18n ( "File %1 successfully removed"  , QString("/etc/ppp/pap-secrets" )), KVpncEnum::debug );
                  //        papSecretsFile.setName("/etc/ppp/pap-secrets2");
                  if ( papSecretsFile.open ( QIODevice::WriteOnly ) )
                  {
                   stream.setDevice ( &papSecretsFile );
                   stream << papsecret_content;
                   papSecretsFile.close();
                   if ( GlobalConfig->KvpncDebugLevel > 2 )
                    GlobalConfig->appendLogEntry ( i18n ( "File %1 successfully rewritten"  , QString("/etc/ppp/pap-secrets" )), KVpncEnum::debug );
                  }
                  else
                  {
                    if ( GlobalConfig->KvpncDebugLevel > 2 )
                     GlobalConfig->appendLogEntry ( i18n ( "File %1 rewrite failed"  , QString("/etc/ppp/pap-secrets" )), KVpncEnum::error );
                  }
                 }
                 else
                 {
                   if ( GlobalConfig->KvpncDebugLevel > 2 )
                    GlobalConfig->appendLogEntry ( i18n ( "File %1 remove failed"  , QString("/etc/ppp/pap-secrets" )), KVpncEnum::error );
                 }
                }
                else
                {
                 GlobalConfig->appendLogEntry ( i18n ( "File %1 could not be opened."  , QString("/etc/ppp/pap-secrets" )), KVpncEnum::error );
                }
               }
            */
            if ( allowReconnect && GlobalConfig->currentProfile->getDoReconnectAfterConnectionLost() )
            {
                if ( GlobalConfig->currentProfile->getUseReconnectDelay() )
                {
                    GlobalConfig->appendLogEntry ( i18n ( "Waiting %1s for reconnect..." ).arg ( GlobalConfig->currentProfile->getReconnectDelay() ), KVpncEnum::info );
                    for ( int time = 0; time <= GlobalConfig->currentProfile->getReconnectDelay() * 1000; time += 200 )
                    {
                        usleep ( 200 );
                        GlobalConfig->appPointer->processEvents();
                    }
                }
                //			if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry ( i18n ( "Reconnect after connection lost enabled, reconnecting..." ), KVpncEnum::info );
                connectClicked();
            }
            return ;
        }
        // success
        else if (connectSuccess) {

            sec = hour = min = 0;

            GlobalConfig->status = KVpncEnum::connected;

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

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

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

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

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


            // write pppd.<profile>.up
            QFile pppdupfile(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".up");
            QTextStream pppdupstream(&pppdupfile);
            if (pppdupfile.open(QIODevice::WriteOnly)) {
                pppdupstream <<  "#!" << GlobalConfig->InterpreterShell << "\n";
                pppdupstream << "# generated by kvpnc. Do not edit it." << "\n";
                pppdupstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
                pppdupstream << "cat /etc/resolv.conf > " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << "\n";
                /* update dns? */
                if (GlobalConfig->currentProfile->getUseDnsUpdate()) {
                    pppdupstream << "if [ -x /sbin/resolvconf ] ; then\n";
                    pppdupstream << " echo > /dev/null" << "\n";
                    pppdupstream << "else" << "\n";
                    pppdupstream << " echo \"# generated by kvpnc. Do not edit it.\" > /etc/resolv.conf" << "\n";
                    pppdupstream << "fi\n";

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

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

                        }

                        pppdupstream << "fi" << "\n";

                        pppdupstream << "# " << "\n";
                    }
                    if ((GlobalConfig->currentProfile->getUseDnsServer() && !GlobalConfig->currentProfile->getDnsServer().isEmpty()) || (GlobalConfig->currentProfile->getUseSearchDomainInResolvConf()  && ! !GlobalConfig->currentProfile->getSearchDomainInResolvConf().isEmpty())) {
                        pppdupstream << "if [  -x /sbin/resolvconf ] ; then\n";
                        pppdupstream << " dev=$1\n";
                        pppdupstream << " if [ -z $dev ] ; then\n";
                        pppdupstream << "  dev=\"ppp0\"\n";
                        pppdupstream << " fi\n";

                        if (GlobalConfig->currentProfile->getUseDnsServer() && !GlobalConfig->currentProfile->getDnsServer().isEmpty())
                            resolvtemp += "nameserver " + GlobalConfig->currentProfile->getDnsServer() + "\n";
                        if (GlobalConfig->currentProfile->getUseSearchDomainInResolvConf() && !GlobalConfig->currentProfile->getSearchDomainInResolvConf().isEmpty())
                            resolvtemp += "search " + GlobalConfig->currentProfile->getSearchDomainInResolvConf() + "\n";
                        pppdupstream << "else\n";
                        if (GlobalConfig->currentProfile->getUseDnsServer() && !GlobalConfig->currentProfile->getDnsServer().isEmpty()) {
                            pppdupstream << "echo \"nameserver " << GlobalConfig->currentProfile->getDnsServer() + "\" >> /etc/resolv.conf\n";
                            no_nameserver = false;
                        }
                        if (GlobalConfig->currentProfile->getUseSearchDomainInResolvConf() && !GlobalConfig->currentProfile->getSearchDomainInResolvConf().isEmpty())
                            pppdupstream << "echo \"search " << GlobalConfig->currentProfile->getSearchDomainInResolvConf() + "\" >> /etc/resolv.conf\n";
                        pppdupstream << "fi\n";
                    }


                    pppdupstream << "if [ -x /sbin/resolvconf ] ; then\n";
                    pppdupstream << " echo \"" + resolvtemp + "\" > " + tmpPath + "resolvconf." + GlobalConfig->currentProfile->getName() << "\n";

                    if (no_nameserver == true) {
                        pppdupstream << "   cat   " + tmpPath + "/resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() + " | grep nameserver >> " + tmpPath + "resolvconf." + GlobalConfig->currentProfile->getName() + "\n";
                    }
                    pppdupstream << " cat   " + tmpPath + "resolvconf." + GlobalConfig->currentProfile->getName() +" | /sbin/resolvconf -a $dev\n";

                    /* crissi: -u seems not nessary */
                    //pppdupstream << " cat   " + tmpPath + "/pppd.resolvconf.tmp | /sbin/resolvconf -u\n";

                    if (!GlobalConfig->holdGeneratedScripts)
                        pppdupstream << " rm -f " + tmpPath + "resolvconf." + GlobalConfig->currentProfile->getName()+ "\n";

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

                    pppdupstream << "fi\n";
                    //pppdupstream << "chmod u-w  /etc/resolv.conf\n";
                } else {
                    /* dont update dns */
                    setenv("DNS_UPDATE", "NO", 1);
                }

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

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

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

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

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

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

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

                    }
                    if (defaultroutecount > 1) {
                        pppdupstream << "newdefaultgw=$(" << GlobalConfig->pathToIp << " route show default | grep default | grep -v " + GlobalConfig->OldDefaultGw + ")" << "\n";
                        pppdupstream << "if [ -z $newdefaultgw ]; then" << "\n";
                        pppdupstream << " newdefaultgw=\"" << GlobalConfig->OldDefaultGw << "\"" << "\n";
                        pppdupstream << "fi" << "\n";
                        for (int i = 0; i < defaultroutecount; i++) {
                            pppdupstream << GlobalConfig->pathToRoute << " del default" << "\n";
                        }
//       pppdupstream << GlobalConfig->pathToIp + " route add 0.0.0.0 via " << GlobalConfig->OldDefaultGw << " dev " << pppdev << "\n";
                        pppdupstream << GlobalConfig->pathToRoute << " add default " << pppdev << "\n";

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

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

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


//     NetworkInterface iface(GlobalConfig,GlobalConfig->appPointer, this);
//     GlobalConfig->NewDefaultGw = iface.getGatewayOfDefaultInterface();
//
//     if (GlobalConfig->NewDefaultGw != "0.0.0.0")
//     {
//      if ( GlobalConfig->KvpncDebugLevel > 3 )
//       GlobalConfig->appendLogEntry ( i18n ( "Setting extra route: %1 over %2 gw %3" , QString( "0.0.0.0" ), pppdev , GlobalConfig->NewDefaultGw), KVpncEnum::debug );
//      pppdupstream << GlobalConfig->pathToIp + " route add 0.0.0.0 via " << GlobalConfig->NewDefaultGw << " dev " << pppdev << "\n";
                }
                else {
                    if (GlobalConfig->KvpncDebugLevel > 3)
                        GlobalConfig->appendLogEntry(i18n("replacing default route: %1"  , QString(i18n("no"))), KVpncEnum::debug);
                }
                pppdupfile.close();
            }


            QProcess pppdUpProcess(this);
            QString proc = GlobalConfig->InterpreterShell;
            QStringList args;
            args.append(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".up");
            pppdUpProcess.setEnvironment(*env);
            pppdUpProcess.start(proc, args);
            if (!pppdUpProcess.waitForStarted()) {
                KMessageBox::sorry(this, i18n("\"%1\" (%2) start failed."  , QString("PppdUpScript") , QString(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".up")));
            } else {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("\"%1\" (%2) started." , QString("PppdUpScript")  , QString(tmpPath + "pppd." + GlobalConfig->currentProfile->getName() + ".up")) , KVpncEnum::debug);
                waitForFinished(&pppdUpProcess, 100);

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

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

            if (GlobalConfig->KvpncDebugLevel > 2) {
                GlobalConfig->appendLogEntry(i18n("Local IP address: %1, remote IP address: %2, device: %3, speed: %4",
                                                  QString(TunnelInterfaceIP),
                                                  ipremote,
                                                  ifname,
                                                  speed),
                                             KVpncEnum::debug);
            }

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


            {


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

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

void KVpnc::readFromStderr_pptp()
{
    QStringList msg_list = QString(PptpProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        if ( !msg.isEmpty() && GlobalConfig->KvpncDebugLevel > 4 )
        {
            GlobalConfig->appendLogEntry ( "[pptp err raw]: "+msg, KVpncEnum::debug );
        }


        bool abort = false;
        bool error_found = false;
        bool allowReconnect = false;

        if (msg.indexOf("DNS address", 0, Qt::CaseInsensitive) || msg.indexOf("Script /etc/ppp/ip-up started", 0, Qt::CaseInsensitive))
            GlobalConfig->appendLogEntry("[pppd] " + msg, KVpncEnum::debug);
        else
            GlobalConfig->appendLogEntry("[pppd err] " + msg, KVpncEnum::error);

        if (msg.indexOf("authentication failed", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Authentication has failed."));
            GlobalConfig->appendLogEntry(i18n("Authentication has failed.") , KVpncEnum::error);
            //abort = true;
            AuthRetry = true;
            GlobalConfig->haveUserData = false;
//             disconnectClicked();
// 			while(GlobalConfig->status != KVpncEnum::disconnected) {
// 				usleep(500);
// 				if (GlobalConfig->appPointer->hasPendingEvents())
// 					GlobalConfig->appPointer->processEvents();
// 			}
            connectClicked();
            return;

        } else if (msg.indexOf("MPPE required but not available", 0, Qt::CaseInsensitive) > -1) {
            if (error_found == false)
                KMessageBox::error(this, i18n("MPPE required but not available"));
            GlobalConfig->appendLogEntry(i18n("MPPE required but not available") , KVpncEnum::error);
            abort = true;
            error_found = true;
        } else if (msg.indexOf("peer refused to authenticate", 0, Qt::CaseInsensitive) > -1) {
            if (error_found == false)
                KMessageBox::error(this, i18n("The peer refused to authenticate."));
            GlobalConfig->appendLogEntry(i18n("The peer refused to authenticate.") , KVpncEnum::error);
            abort = true;
            error_found = true;
        } else if (msg.indexOf("could not find module", 0, Qt::CaseInsensitive) > -1) {
            if (error_found == false)
                KMessageBox::error(this, i18n("Module not found."));
            GlobalConfig->appendLogEntry(i18n("Module not found."), KVpncEnum::error);
            abort = true;
            error_found = true;
        } else if (msg.indexOf("Connection terminated.", 0, Qt::CaseInsensitive) > -1) {
            if (error_found==false)
                if ( !GlobalConfig->currentProfile->getDoReconnectAfterConnectionLost() )
                    KMessageBox::error( this, i18n( "Connection has been terminated." ) );
            GlobalConfig->appendLogEntry(i18n("Connection has been terminated."), KVpncEnum::info);
            abort = true;
            error_found = true;
            allowReconnect = true;
        } else if (msg.indexOf("tcflush failed: Bad file descriptor", 0, Qt::CaseInsensitive) > -1) {
            if (error_found == false)
                if (!GlobalConfig->currentProfile->getDoReconnectAfterConnectionLost())
                    KMessageBox::error(this, i18n("Sending data has failed. Connection was terminated."));
            GlobalConfig->appendLogEntry(i18n("Sending data has failed. Connection was terminated."), KVpncEnum::error);
            abort = true;
            error_found = true;
            allowReconnect=true;
        } else if (msg.indexOf("MPPE required, but kernel has no support", 0, Qt::CaseInsensitive) > -1) {
            if (error_found == false)
                KMessageBox::error(this, i18n("MPPE required, but kernel has no support. Please use a kernel with mppe support."));
            GlobalConfig->appendLogEntry(i18n("MPPE required, but kernel has no support. Please use a kernel with mppe support.") , KVpncEnum::error);
            abort = true;
            error_found = true;
        } else if (msg.indexOf("unrecognized option 'mppe'", 0, Qt::CaseInsensitive) > -1) {
            if (error_found == false)
                KMessageBox::error(this, i18n("MPPE required, but pppd has no MPPE support. Please install a pppd with MPPE support."));
            GlobalConfig->appendLogEntry(i18n("MPPE required, but pppd has no support. Please install a pppd with MPPE support.") , KVpncEnum::error);
            abort = true;
            error_found = true;
        } else if (msg.indexOf("Input/output error", 0, Qt::CaseInsensitive) > -1) {
            if (error_found==false)
                if ( !GlobalConfig->currentProfile->getDoReconnectAfterConnectionLost() )
                    KMessageBox::error( this, i18n( "Input/output error" ) );
            GlobalConfig->appendLogEntry(i18n("Input/output error") , KVpncEnum::error);
            abort = true;
            error_found = true;
            allowReconnect = true;
        } else if (msg.indexOf("local IP address", 0, Qt::CaseInsensitive) > -1) {
            TunnelInterfaceIP = msg.simplified().section(' ', 3, 3);
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Tunnel IP address: %1\n" , TunnelInterfaceIP), KVpncEnum::debug);
            abort = false;
            error_found = true;
        } else if (msg.indexOf("No auth is possible sent", 0, Qt::CaseInsensitive) > -1) {
            if (error_found == false)
                KMessageBox::error(this, i18n("No password was send. Please check if there is a password set in user settings."));
            GlobalConfig->appendLogEntry(i18n("No password was send. Please check if there is a password set in user settings.") , KVpncEnum::error);
            abort = true;
            error_found = true;
        }

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

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

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

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

void KVpnc::readOutput_openvpn()
{

    if (OpenvpnProcess) {
        QString ProcessMsg = "";
        bool stderr = false;
        bool connectSuccess = false;
        QString NetworkDevice = "";

        QStringList msg_list = QString(OpenvpnProcess->readAllStandardOutput()).split('\n');
        for (int i = 0; i < msg_list.size(); ++i) {
            QString msg = msg_list.at(i);


            if (!msg.isEmpty() && GlobalConfig->KvpncDebugLevel > 4) {
                GlobalConfig->appendLogEntry("[openvpn raw]: " + msg, KVpncEnum::debug);
            }
            //  else
            //  {
            //   stderr=true;
            //    msg = QString( OpenvpnProcess->readStderr() );
            //   GlobalConfig->appendLogEntry ( "stderr openvpn: "+msg, KVpncEnum::debug );
            //  }


            if (msg.indexOf("refused", 0, Qt::CaseInsensitive) > -1 && !stderr)
                GlobalConfig->appendLogEntry("[openvpn] " + msg, KVpncEnum::error);
            else if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry("[openvpn] " + msg, KVpncEnum::debug);

            bool abort = false;

            if (msg.indexOf("Connection timed out", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("Connection has been timed out. Terminate."));
                GlobalConfig->appendLogEntry(i18n("Connection has been timed out. Terminate.") , KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("[ECONNREFUSED]: Connection refused", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("Connection has been refused. Terminate."));
                GlobalConfig->appendLogEntry(i18n("Connection has been refused. Terminate.") , KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("AUTH: Received AUTH_FAILED", 0, Qt::CaseInsensitive) > -1) {
                AuthRetry = true;
                GlobalConfig->haveUserData = false;
                disconnect(OpenvpnProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutput_openvpn()));
                //     disconnect( OpenvpnProcess, SIGNAL( readyReadStandardError() ), this, SLOT( readOutput_openvpn() ) );
                connectClicked();
                //   KMessageBox::error( this, i18n( "Authentication failed (%1)." ,i18n("user password") ));
                GlobalConfig->appendLogEntry(i18n("Authentication failed (%1)." , i18n("user password")) , KVpncEnum::error);
                //   abort=true;
            } else if (msg.indexOf("ERROR: could not read Auth username/password from management interface", 0, Qt::CaseInsensitive) > -1) {
                ;
                disconnect(OpenvpnProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutput_openvpn()));
                //     disconnect( OpenvpnProcess, SIGNAL( readyReadStandardError() ), this, SLOT( readOutput_openvpn() ) );
                connectClicked();
                //   KMessageBox::error( this, i18n( "Authentication failed (%1)." ,i18n("user password") ));
                GlobalConfig->appendLogEntry(i18n("Username and password could not be read from management interface.") , KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("ERROR: could not read eToken token username/password/ok from management interface", 0, Qt::CaseInsensitive) > -1) {
                disconnect(OpenvpnProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutput_openvpn()));
                //     disconnect( OpenvpnProcess, SIGNAL( readyReadStandardError() ), this, SLOT( readOutput_openvpn() ) );
                connectClicked();
                //   KMessageBox::error( this, i18n( "Authentication failed (%1)." ,i18n("user password") ));
                GlobalConfig->appendLogEntry(i18n("eToken password could not be read from management interface.") , KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("Insufficient key material or header text not found", 0, Qt::CaseInsensitive) > -1) {
                AuthRetry = true;
                GlobalConfig->haveUserData = false;
                disconnect(OpenvpnProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutput_openvpn()));
                //     disconnect( OpenvpnProcess, SIGNAL( readyReadStandardError() ), this, SLOT( readOutput_openvpn() ) );
                connectClicked();
                //   KMessageBox::error( this, i18n( "Authentication failed (%1)." ,i18n("user password") ));
                GlobalConfig->appendLogEntry(i18n("Insufficient key material or header text not found.") , KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("not found", 0, Qt::CaseInsensitive) > -1 && msg.indexOf("Message hash algorithm", 0, Qt::CaseInsensitive) > -1) {
                QString hash_algo = msg.section("'", 1, 1);
                KMessageBox::error(this, i18n("Hash algorithm \"%1\" not found. Please choose another one." , hash_algo));
                GlobalConfig->appendLogEntry(i18n("Hash algorithm \"%1\" not found. Please choose another one." , hash_algo) , KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("Cannot load private key file", 0, Qt::CaseInsensitive) > -1) {
                //KMessageBox::error( this, i18n( "Auth username is empty." ) );
                GlobalConfig->appendLogEntry(i18n("Private key file could not be loaded.") , KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("'dev-type' is used inconsistently, local='dev-type tun', remote='dev-type tap'", 0, Qt::CaseInsensitive) > -1) {
                //    KMessageBox::error( this, i18n( "Local network type is %1 but remote network type is %2. This must be fixed.\nGo to OpenVPN settings and change it to %2." , QString("tun") , QString("tap") ) );
                //    GlobalConfig->appendLogEntry( i18n( "Local network type is %1 but remote network type is %2. This must be fixed." , QString("tun") , QString("tap") ) , KVpncEnum::error );
                //    abort = true;

                GlobalConfig->appendLogEntry(i18n("Local network type is %1 but remote network type is %2. This will be fixed." , QString("tun") , QString("tap")), KVpncEnum::info);
                GlobalConfig->currentProfile->setTunnelDeviceType("tap");
                GlobalConfig->saveOptions(true, GlobalConfig->currentProfile->getName());
                disconnectClicked();
                connectClicked();
            } else if (msg.indexOf("'dev-type' is used inconsistently, local='dev-type tap', remote='dev-type tun'", 0, Qt::CaseInsensitive) > -1) {
                //    KMessageBox::error( this, i18n( "Local network type is %1 but remote network type is %2. This must be fixed.\nGo to OpenVPN settings and change it to %2." , "tap" , "tun" ) );
                //    GlobalConfig->appendLogEntry( i18n( "Local network type is %1 but remote network type is %2. This must be fixed." , "tap" , "tun" ), KVpncEnum::error );
                //    abort = true;

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

                GlobalConfig->appendLogEntry(i18n("Connection was rejected (wrong HTTP proxy auth data?)." , GlobalConfig->currentProfile->getHttpProxy() , GlobalConfig->currentProfile->getHttpProxyPort()) , KVpncEnum::error);
                KMessageBox::error(this, i18n("Connection was rejected (wrong HTTP proxy auth data?)."));
                abort = true;
            } else if (msg.indexOf("MANAGEMENT: Cannot bind TCP socket", 0, Qt::CaseInsensitive) > -1) {

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

                abort = true;
            } else if (msg.indexOf(QString("MANAGEMENT: Socket bind failed on local address 127.0.0.1:" + QString().setNum(GlobalConfig->OpenvpnManagementPort) + ": Address already in use"), 0, Qt::CaseInsensitive) > -1) {

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

                QString NameAndPid = Utils(GlobalConfig).getNameAndPidOfProgramListen(GlobalConfig->OpenvpnManagementPort);
                GlobalConfig->appendLogEntry(i18n("NameAndPid: %1" , NameAndPid) , KVpncEnum::debug);
                int pid = -1;
                QString Name = "";
                if (!NameAndPid.isEmpty()) {
                    pid = NameAndPid.section('/', 0, 0).toInt();
                    Name = NameAndPid.section('/', 1, 1);
                    KMessageBox::error(this, i18n("Binding port %1 failed. Program \"%2\" with PID \"%3\" is using it. You have to stop it first." , QString().setNum(GlobalConfig->OpenvpnManagementPort) , Name , QString().setNum(pid)));
                } else {
                    KMessageBox::error(this, i18n("Port binding failed"));
                    GlobalConfig->appendLogEntry(i18n("Port binding failed") , KVpncEnum::error);
                }
                abort = true;
                //    managementhandler->closeConnection();
            } else if (msg.indexOf("TLS key negotiation failed to occur within 60 seconds", 0, Qt::CaseInsensitive) > -1 || msg.indexOf("TLS Error: TLS handshake failed", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("TLS key negotiation failed to occur within 60 seconds"));
                GlobalConfig->appendLogEntry(i18n("Port binding failed") , KVpncEnum::error);
                abort = true;
            }
            /*
            else if ( msg.indexOf( "authentication failed", 0, Qt::CaseInsensitive ) > -1 )
            {
            KMessageBox::error( this, i18n( "Authentication has failed." ) );
            abort = true;
            }
            */
            else if (msg.indexOf("Enter Private Key Password", 0, Qt::CaseInsensitive) > -1) {

                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Private key password requested, send it...\n"), KVpncEnum::debug);

                QString PrivKeyPassStr = "";
                //   if (GlobalConfig->currentProfile->getSavePsk())
                PrivKeyPassStr = GlobalConfig->currentProfile->getPrivateKeyPass();
                //   else
                //    PrivKeyPassStr = TmpPrivKeyPassStr;
                if (PrivKeyPassStr.isEmpty()) {
                    GlobalConfig->TmpPrivateKeyPass = "";
                    QString pass = "";
                    EnterXauthInteractivePasscodeDialog dlg(0);
                    dlg.setWindowTitle(i18n("Enter private key password"));
                    dlg.main->DescriptionLabel->setText(i18n("Enter private key password to unlock private key:"));
                    dlg.main->LabelPassword->setText(i18n("Private key password:"));
                    dlg.main->SavePasswordCheckBox->setText(i18n("Save private key password"));
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry("[openvpn] " + i18n("Password for private key requested...\n"), KVpncEnum::debug);
                    if (dlg.exec()) {

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

                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry("OpenvpnManagementHandler: " + i18n("private key password got from user"), KVpncEnum::debug);

                            if (dlg.main->SavePasswordCheckBox->isChecked()) {
                                GlobalConfig->currentProfile->setSavePrivateKeyPassword(true);
                                GlobalConfig->currentProfile->setPrivateKeyPass(QString(pass));
                            }

                            GlobalConfig->TmpPrivateKeyPass = QString(pass);

                            //             if ( GlobalConfig->KvpncDebugLevel > 5 )
                            //     GlobalConfig->appendLogEntry( "OpenvpnManagementHandler: private key password: " + GlobalConfig->TmpPrivateKeyPass, KVpncEnum::debug );

                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry("OpenvpnManagementHandler: " + i18n("Send private key password..."), KVpncEnum::debug);

                            OpenvpnProcess->write(PrivKeyPassStr.toUtf8());
                            OpenvpnProcess->write("\n");
                        } else {
                            GlobalConfig->appendLogEntry("OpenvpnManagementHandler: password empty, stop.", KVpncEnum::error);
                            return;
                        }
                    }
                } else {
                    OpenvpnProcess->write(PrivKeyPassStr.toUtf8());
                    OpenvpnProcess->write("\n");
                    return ;
                }
            } else if (msg.indexOf("Enter Auth Username", 0, Qt::CaseInsensitive) > -1) {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Username requested, send it...\n"), KVpncEnum::debug);

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

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

                OpenvpnProcess->write(UsernameStr.toUtf8());
                OpenvpnProcess->write("\n");

                return ;
            } else if (msg.indexOf("Enter Auth Password:", 0, Qt::CaseInsensitive) > -1) {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("User password requested, send it...\n"), KVpncEnum::debug);

                if (!GlobalConfig->currentProfile->getSaveUserPassword() && !AuthRetry)
                    OpenvpnProcess->write(GlobalConfig->currentProfile->getUserPassword().toUtf8());
                else {
                    //     if ( GlobalConfig->KvpncDebugLevel > 0 )
                    //      GlobalConfig->appendLogEntry ( "OpenVPN Auth Pass: " + GlobalConfig->TmpPassword , KVpncEnum::debug );


                    OpenvpnProcess->write(GlobalConfig->TmpPassword.toUtf8());
                    OpenvpnProcess->write("\n");
                }

            } else if (msg.indexOf("Cannot resolve host address", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("Host could not be resolved."));
                GlobalConfig->appendLogEntry(i18n("Host could not be resolved."), KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("could not find module", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("Module not found."));
                GlobalConfig->appendLogEntry(i18n("Module not found.") , KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("Socket bind failed on local address", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("Binding to socket on local address failed."));
                GlobalConfig->appendLogEntry(i18n("Binding to socket on local address failed.") , KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("No route to host", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("No route to host found."));
                GlobalConfig->appendLogEntry(i18n("No route to host found.") , KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("Connection terminated", 0, Qt::CaseInsensitive) > -1) {
                //   KMessageBox::error( this, i18n( "Connection has been terminated." ) );
                abort = true;
            } else if (msg.indexOf("Cannot open file key file", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("Cannot open the preshared key file."));
                GlobalConfig->appendLogEntry(i18n("Cannot open the preshared key file.") , KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("Authenticate/Decrypt packet error: cipher final failed", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("Authentication has failed because decryption failure. Please check OpenVPN settings."));
                GlobalConfig->appendLogEntry(i18n("Authentication has failed because decryption failure. Please check OpenVPN settings.") , KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("'auth' is used inconsistently", 0, Qt::CaseInsensitive) > -1) {
                QString LocalAuth = msg.section('=', 1, 1).section(',', 0, 0).section(' ', 1, 1).remove("'", Qt::CaseSensitive);
                QString PeerAuth = msg.section('=', 2, 2).section(' ', 1, 1).remove("'", Qt::CaseSensitive);
                //    KMessageBox::error( this, i18n( "Wrong authentication method used. We use \"%1\" but peer wants \"%2\". Please change it in %3 settings." , LocalAuth , PeerAuth , i18n( "OpenVPN" ) ) );
                //    GlobalConfig->appendLogEntry( i18n( "Wrong authentication method used. We use \"%1\" but peer wants \"%2\". Please change it in %3 settings." , LocalAuth , PeerAuth , i18n( "OpenVPN" ) ) , KVpncEnum::error );
                //    abort = true;

                GlobalConfig->appendLogEntry(i18n("Wrong authentication method used. We use \"%1\" but peer wants \"%2\", this will be fixed." , LocalAuth , PeerAuth , i18n("OpenVPN")) , KVpncEnum::info);
                GlobalConfig->currentProfile->setUseAuthenticationAlgorithm(true);
                GlobalConfig->currentProfile->setAuthenticationAlgorithm(PeerAuth);
                GlobalConfig->saveOptions(true, GlobalConfig->currentProfile->getName());
                disconnectClicked();
                connectClicked();
            } else if (msg.indexOf("WARNING: 'cipher' is used inconsistently", 0, Qt::CaseInsensitive) > -1) {
                // example: WARNING: 'cipher' is used inconsistently, local='cipher BF-CBC', remote='cipher AES-128-CBC'
                QString LocalCipher = msg.section('=', 1, 1).section(',', 0, 0).section(' ', 1, 1).remove("'", Qt::CaseSensitive);
                QString PeerCipher = msg.section('=', 2, 2).section(' ', 1, 1).remove("'", Qt::CaseSensitive);
                //    KMessageBox::error( this, i18n( "Wrong cipher used. We use \"%1\" but peer wants \"%2\". Please change it in %3 settings." , LocalCipher , PeerCipher , i18n( "OpenVPN" ) ) );
                //    GlobalConfig->appendLogEntry( i18n( "Wrong chiper used. We use \"%1\" but peer wants \"%2\". Please change it in %3 settings." , LocalCipher , PeerCipher , i18n( "OpenVPN" ) ) , KVpncEnum::error );
                //    abort = true;

                GlobalConfig->appendLogEntry(i18n("Wrong chipher used. We use \"%1\" but peer wants \"%2\", this will be fixed." , LocalCipher , PeerCipher , i18n("OpenVPN")) , KVpncEnum::info);
                GlobalConfig->currentProfile->setUserdefiniedCipher(PeerCipher);
                GlobalConfig->currentProfile->setUseUserdefiniedCipher(true);
                GlobalConfig->saveOptions(true, GlobalConfig->currentProfile->getName());
                disconnectClicked();
                connectClicked();
            } else if (msg.indexOf("Options error: Unrecognized option or missing parameter(s) in [PUSH-OPTIONS]", 0, Qt::CaseInsensitive) > -1) {
                //    KMessageBox::error( this, i18n( "OpenVPN configuration error. Unrecognized option or missing parameter(s) in [PUSH-OPTIONS]" ) );
                //    GlobalConfig->appendLogEntry( i18n( "OpenVPN configuration error. Unrecognized option or missing parameter(s) in [PUSH-OPTIONS]" ), KVpncEnum::error );
                //    abort = true;
                GlobalConfig->appendLogEntry(i18n("OpenVPN configuration error. Unrecognized option or missing parameter(s) in [PUSH-OPTIONS]."), KVpncEnum::info);
                abort = false;
            } else if (msg.indexOf("Options error: Unrecognized option or missing parameter", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("OpenVPN configuration error. Unrecognized option or missing parameter."));
                GlobalConfig->appendLogEntry(i18n("OpenVPN configuration error. Unrecognized option or missing parameter."), KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("Options error: Parameter", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("OpenVPN configuration error. Wrong parameter in config file. Please contact the KVpnc author."));
                GlobalConfig->appendLogEntry(i18n("OpenVPN configuration error. Wrong parameter in config file. Please contact the KVpnc author."), KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("TCP connection established", 0, Qt::CaseInsensitive) > -1) {
                GlobalConfig->appendLogEntry("[openvpn]: " + i18n("Low level connection to %1 established." , QString(GlobalConfig->currentProfile->getGateway())), KVpncEnum::info);
            } else if (msg.indexOf("UDP connection established", 0, Qt::CaseInsensitive) > -1) {
                GlobalConfig->appendLogEntry("[openvpn]: " + i18n("Low level connection to %1 established." , GlobalConfig->currentProfile->getGateway()), KVpncEnum::info);
            }
            //   else if ( msg.indexOf( "Options error", 0, Qt::CaseInsensitive ) > -1 )
            //   {
            //    KMessageBox::error( this, i18n( "OpenVPN configuration error." ) );
            //    GlobalConfig->appendLogEntry( i18n( "OpenVPN configuration error." ), KVpncEnum::error );
            //    GlobalConfig->currentProfile->setDoReconnectAfterConnectionLost( false );
            //    abort = true;
            //   }
            else if (msg.indexOf("refused", 0, Qt::CaseInsensitive) > -1) {
                //KMessageBox::error( this, i18n( "Connection to OpenVPN server was refused." ) );
                abort = false;
            } else if (msg.indexOf("Connection timed out", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("Connection has been timed out. Terminate."));
                GlobalConfig->appendLogEntry(i18n("Connection has been timed out. Terminate.") , KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("Cannot load certificate file", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("Certificate file (%1) could not be load. Please check path of it." , GlobalConfig->currentProfile->getX509Certificate()));
                GlobalConfig->appendLogEntry(i18n("Certificate file (%1) could not be load. Please check path of it." , GlobalConfig->currentProfile->getX509Certificate()) , KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("ifconfig failed", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("ifconfig has failed."));
                GlobalConfig->appendLogEntry(i18n("ifconfig has failed.") , KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("Auth username is empty", 0, Qt::CaseInsensitive) > -1) {
                //KMessageBox::error( this, i18n( "Auth username is empty." ) );
                GlobalConfig->appendLogEntry(i18n("Auth username is empty.") , KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("Cannot load private key file", 0, Qt::CaseInsensitive) > -1) {
                //KMessageBox::error( this, i18n( "Auth username is empty." ) );
                GlobalConfig->appendLogEntry(i18n("Private key file could not be loaded.") , KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("Need 'token-insertion-request' confirmation MSG:Please insert SLOT", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("Need token to be insert. Please insert token in SLOT...."));
                GlobalConfig->appendLogEntry(i18n("Need token to be insert. Please insert token in SLOT...."), KVpncEnum::error);
                abort = true;
            } else if (msg.indexOf("process exiting", 0, Qt::CaseInsensitive) > -1) {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("%1 is shutting down." , QString("openvpn")), KVpncEnum::debug);

                connectionEnded();
                setGuiStatus(KVpncEnum::disconnected);
            } else if (msg.indexOf("Initialization Sequence Completed", 0, Qt::CaseInsensitive) > -1) {
                connectSuccess = true;
            } else if (msg.indexOf("TUN/TAP device", 0, Qt::CaseInsensitive) > -1) {
                // TUN/TAP device tun0 opened
                NetworkDevice = msg.section(' ', -2, -2);    // tun0
                OpenvpnDevice = msg.section(' ', -2, -2);    // tun0
                TunnelInterfaceIP = msg.section(' ', -5, -5);    // ip
                NetworkInterface iface(GlobalConfig, parent);
                TunnelInterfaceIP = iface.getInterfaceIP(OpenvpnDevice);

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

            // success
            if (connectSuccess) {

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

                sec = hour = min = 0;

                GlobalConfig->status = KVpncEnum::connected;

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

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

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

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

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

                disconnectClicked();

                return ;
            }

        }
    }

}

void KVpnc::readFromStdout_l2tpd()
{
    QStringList msg_list = QString(L2tpdProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        processStdout_l2tpd(msg);
    }
}

void KVpnc::readFromStderr_l2tpd()
{
    QStringList msg_list = QString(L2tpdProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        processStderr_l2tpd(msg);
    }

}

void KVpnc::processStdout_l2tpd(QString msg)
{
    bool NormalMsg = true;
    bool ErrorMsg = false;
    if (GlobalConfig->KvpncDebugLevel > 7)
        GlobalConfig->appendLogEntry(QString("[l2tpd raw] " + msg) , KVpncEnum::debug);


    bool abort = false;
    bool connectSuccess = false;

    if (msg.indexOf("init_network: Unable to bind socket. Terminating", 0, Qt::CaseInsensitive) > -1 || msg.indexOf("Unable to bind socket: Address already in use", 0, Qt::CaseInsensitive) > -1) {
        bool kill_l2tpd = true;

        QString daemon = "xl2tpd";
        if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists()) {
            daemon = "xl2tpd";
            if (!GlobalConfig->doKillXl2tpdIfStillRunning) {
                GlobalConfig->appendLogEntry(QString("[l2tpd err] " +
                                                     i18n("Bind to given port has failed."
                                                          " Another %1 process is running."
                                                          " Please stop %1 first.",
                                                          daemon)),
                                             KVpncEnum::debug);
                abort = true;
                kill_l2tpd = false;
            }
        } else {
            daemon = "l2tpd";
            if (!GlobalConfig->doKillL2tpdIfStillRunning) {
                GlobalConfig->appendLogEntry(QString("[l2tpd err] " +
                                                     i18n("Bind to given port has failed."
                                                          " Another %1 process is running."
                                                          " Please stop %1 first.",
                                                          daemon)),
                                             KVpncEnum::debug);
                abort = true;
                kill_l2tpd = false;
            }
        }

        if (kill_l2tpd == true) {
            QProcess killl2tpdprocess(this);
            QString proc = GlobalConfig->pathToKillall;
            QStringList args;
            if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
                args.append("xl2tpd");
            else
                args.append("l2tpd");
            killl2tpdprocess.setEnvironment(*env);
            killl2tpdprocess.start(proc, args);
            if (!killl2tpdprocess.waitForStarted()) {
                GlobalConfig->appendLogEntry(i18n("l2tpd could not be killed."),
                                             KVpncEnum::error);
                GlobalConfig->appendLogEntry(QString("[l2tpd err] " +
                                                     i18n("Bind to given port has failed."
                                                          " Another %1 process is running."
                                                          " Please stop %1 first.",
                                                          daemon)),
                                             KVpncEnum::debug);
                abort = true;
            } else {
                waitForFinished(&killl2tpdprocess, 100);
                // restart l2tpd
                //       if ( L2tpdProcess != 0)
                //        L2tpdProcess->kill();

                sleep(1);

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

                L2tpdProcess->setEnvironment(*env);
                L2tpdProcess->start(proc, args);
                if (!L2tpdProcess->waitForStarted()) {
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("l2tpd")), KVpncEnum::error);
                    KMessageBox::error(this, i18n("Failed to start \"%1\"." , QString("l2tpd")));
                    setGuiStatus(KVpncEnum::disconnected);
                } else {
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("%1 was already running. It was killed and restarted." , QString("l2tpd")), KVpncEnum::info);
                }

                abort = false;
            }

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


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

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


        // remove kvpnc entries from secrets file
        if (GlobalConfig->currentProfile->getAuthMethod() == "chap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2") {
            // remove kvpnc entries from chap-secerets
            QFile ChapSecretsFile("/etc/ppp/chap-secrets");
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1", QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
            if (ChapSecretsFile.open(QIODevice::ReadOnly)) {
                QString chapsecret_content = "";
                bool kvpnc_start_marker_found = false;
                bool kvpnc_end_marker_found = false;
                QStringList contentlist = QString(ChapSecretsFile.readAll()).split("\n");
                for (int i = 0; i < contentlist.size(); ++i) {
                    QString line = contentlist.at(i);
                    if (line == "# --- generated by kvpnc. Do not edit it.") {
                        kvpnc_end_marker_found = true;
                        if (GlobalConfig->KvpncDebugLevel > 2)
                            GlobalConfig->appendLogEntry(i18n("End marker in %1 found" , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                    }
                    if (line == "# +++ generated by kvpnc. Do not edit it.") {
                        kvpnc_start_marker_found = true;
                        if (GlobalConfig->KvpncDebugLevel > 2)
                            GlobalConfig->appendLogEntry(i18n("Start marker in %1 found" , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                    }

                    if (kvpnc_start_marker_found == false) {
                        chapsecret_content += line;
                        chapsecret_content += '\n';
                    }
                }
                ChapSecretsFile.close();
                if (ChapSecretsFile.remove()) {
                    if (GlobalConfig->KvpncDebugLevel > 2)
                        GlobalConfig->appendLogEntry(i18n("File %1 successfully removed" , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                    //        ChapSecretsFile.setName("/etc/ppp/chap-secrets2");
                    if (ChapSecretsFile.open(QIODevice::WriteOnly)) {
                        QTextStream stream(&ChapSecretsFile);
                        stream << chapsecret_content;
                        ChapSecretsFile.close();
                        if (GlobalConfig->KvpncDebugLevel > 2)
                            GlobalConfig->appendLogEntry(i18n("File %1 successfully rewritten" , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                    } else {
                        if (GlobalConfig->KvpncDebugLevel > 2)
                            GlobalConfig->appendLogEntry(i18n("File %1 rewrite failed" , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
                    }
                } else {
                    if (GlobalConfig->KvpncDebugLevel > 2)
                        GlobalConfig->appendLogEntry(i18n("File %1 remove failed" , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
                }

            } else {
                GlobalConfig->appendLogEntry(i18n("File %1 could not be opened." , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
            }
        }
        if (GlobalConfig->currentProfile->getAuthMethod() == "pap") {
            // remove kvpnc entries from pap-secerets
            QFile papSecretsFile("/etc/ppp/pap-secrets");
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1", QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
            if (papSecretsFile.open(QIODevice::ReadOnly)) {
                QString papsecret_content = "";
                bool kvpnc_start_marker_found = false;
                bool kvpnc_end_marker_found = false;
                QStringList contentlist = QString(papSecretsFile.readAll()).split("\n");
                for (int i = 0; i < contentlist.size(); ++i) {
                    QString line = contentlist.at(i);
                    if (line == "# --- generated by kvpnc. Do not edit it.") {
                        kvpnc_end_marker_found = true;
                        if (GlobalConfig->KvpncDebugLevel > 2)
                            GlobalConfig->appendLogEntry(i18n("End marker in %1 found" , QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
                    }
                    if (line == "# +++ generated by kvpnc. Do not edit it.") {
                        kvpnc_start_marker_found = true;
                        if (GlobalConfig->KvpncDebugLevel > 2)
                            GlobalConfig->appendLogEntry(i18n("Start marker in %1 found" , QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
                    }

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

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

    } else {
        // success
        if (connectSuccess) {

            sec = hour = min = 0;

            GlobalConfig->status = KVpncEnum::connected;

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


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

            sleep(2);

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

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


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

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

}

void KVpnc::processStderr_l2tpd(QString msg)
{

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



    if (GlobalConfig->KvpncDebugLevel > 7)
        GlobalConfig->appendLogEntry(QString("[l2tpd err raw] " + msg) , KVpncEnum::debug);
    //
//   if ( msg.length() > 3 )
    {

        //   GlobalConfig->appendLogEntry ( QString( "[l2tpd err] " + msg ) , KVpncEnum::error );


        if (msg.indexOf("Maximum retries exceeded for tunnel", 0, Qt::CaseInsensitive) > -1) {
            ErrorMsg = true;
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(QString("[l2tpd] " + i18n("Maximum number of L2TP connect retries exceeded for tunnel, waiting a moment....")) , KVpncEnum::debug);
            abort=true;
        } else if (msg.indexOf("l2tp_call:Connecting to host", 0, Qt::CaseInsensitive) > -1) {
            NormalMsg = true;
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(QString("[l2tpd] " + i18n("l2tp_call:Connecting to host")) , KVpncEnum::debug);
            //    abort=true;
        } else if (msg.indexOf("maximum retries exceeded.", 0, Qt::CaseInsensitive) > -1) {
            ErrorMsg = true;
            GlobalConfig->appendLogEntry(QString("[l2tpd err] " + i18n("Maximum number of L2TP connect retries exceeded, giving up.")) , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("Connection closed to", 0, Qt::CaseInsensitive) > -1) {
            ErrorMsg = true;
            GlobalConfig->appendLogEntry(QString("[l2tpd err] " + i18n("Connection was closed.")) , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("pppd exited for call", 0, Qt::CaseInsensitive) > -1) {
            ErrorMsg = true;
            GlobalConfig->appendLogEntry(QString("[l2tpd err] " + i18n("pppd exited for call.")) , KVpncEnum::error);
            abort = true;
        } else if (msg.indexOf("Unable to load config file", 0, Qt::CaseInsensitive) > -1) {
            ErrorMsg = true;
            KMessageBox::error(this, i18n("Syntax error in config detected. Please report that to the KVpnc maintainer."));
            GlobalConfig->appendLogEntry(QString("[l2tpd err] " + i18n("Error in generated config file for l2tpd, please report to maintainer.")) , KVpncEnum::error);
            abort = true;
        }

        else if (msg.indexOf("init_network: Unable to bind socket. Terminating", 0, Qt::CaseInsensitive) > -1 || msg.indexOf("Unable to bind socket: Address already in use", 0, Qt::CaseInsensitive) > -1) {
            ErrorMsg = true;
            bool kill_l2tpd = true;

            QString daemon = "xl2tpd";
            if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists()) {
                daemon = "xl2tpd";
                if (!GlobalConfig->doKillXl2tpdIfStillRunning) {
                    GlobalConfig->appendLogEntry(QString("[l2tpd err] " +
                                                         i18n("Bind to given port has failed."
                                                              " Another %1 process is running."
                                                              " Please stop %1 first.",
                                                              daemon)),
                                                 KVpncEnum::debug);
                    abort = true;
                    kill_l2tpd = false;
                }
            } else {
                daemon = "l2tpd";
                if (!GlobalConfig->doKillL2tpdIfStillRunning) {
                    GlobalConfig->appendLogEntry(QString("[l2tpd err] " +
                                                         i18n("Bind to given port has failed."
                                                              " Another %1 process is running."
                                                              " Please stop %1 first.",
                                                              daemon)),
                                                 KVpncEnum::debug);
                    abort = true;
                    kill_l2tpd = false;
                }
            }

            if (kill_l2tpd == true) {
                QProcess killl2tpdprocess(this);
                QString proc = GlobalConfig->pathToKillall;
                QStringList args;
                if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
                    args.append("xl2tpd");
                else
                    args.append("l2tpd");
                killl2tpdprocess.setEnvironment(*env);
                killl2tpdprocess.start(proc, args);
                if (!killl2tpdprocess.waitForStarted()) {
                    GlobalConfig->appendLogEntry(i18n("%1 could not be killed." , QString("l2tpd")) , KVpncEnum::error);
                    GlobalConfig->appendLogEntry(QString("[l2tpd err] " +
                                                         i18n("Bind to given port has failed."
                                                              " Another %1 process is running."
                                                              " Please stop %1 first.",
                                                              daemon)),
                                                 KVpncEnum::debug);
                    abort = true;
                } else {
                    waitForFinished(&killl2tpdprocess, 100);

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

                    sleep(1);

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

                    L2tpdProcess->setEnvironment(*env);
                    L2tpdProcess->start(proc, args);
                    if (!L2tpdProcess->waitForStarted()) {
                        if (GlobalConfig->KvpncDebugLevel > 0)
                            GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("l2tpd")), KVpncEnum::error);
                        KMessageBox::error(this, i18n("Failed to start \"%1\"." , QString("l2tpd")));
                        setGuiStatus(KVpncEnum::disconnected);
                    } else {
                        if (GlobalConfig->KvpncDebugLevel > 0)
                            GlobalConfig->appendLogEntry(i18n("%1 was already running. It was killed and restarted." , QString("l2tpd")), KVpncEnum::debug);
                    }

                    abort = false;
                }

            }
        }
        // control_finish: Connection established to 192.168.10.222, 1701.  Local: 55406, Remote: 37911.
        else if (msg.indexOf("Connection established", 0, Qt::CaseInsensitive) > -1) {
            NormalMsg = true;
            GlobalConfig->appendLogEntry(QString("[l2tpd] " + i18n("Low level connection to %1 established."  , QString(GlobalConfig->currentProfile->getGateway()))) , KVpncEnum::success);
            abort = false;
        } else if (msg.indexOf("Call established", 0, Qt::CaseInsensitive) > -1) {
            NormalMsg = true;
            GlobalConfig->appendLogEntry(QString("[l2tpd] " + i18n("Low level connection to %1 established."  , QString(GlobalConfig->currentProfile->getGateway()))) , KVpncEnum::info);
            abort = false;
            if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists()) {
                GlobalConfig->appendLogEntry(QString("[l2tpd] " + i18n("Low level connection %1 established."  , QString(GlobalConfig->currentProfile->getGateway()))) , KVpncEnum::info);

                abort = false;
            }

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

        } else if (msg.indexOf("Connecting to host", 0, Qt::CaseInsensitive) > -1) {
            NormalMsg = true;
            if (GlobalConfig->KvpncDebugLevel > 1)
                GlobalConfig->appendLogEntry(i18n("%1 is connecting to host %2..." , QString("l2tpd"), GlobalConfig->currentProfile->getGateway()), KVpncEnum::debug);
        } else if (msg.indexOf("Listening on IP address", 0, Qt::CaseInsensitive) > -1
                   || msg.indexOf("Calling on tunnel", 0, Qt::CaseInsensitive) > -1) {
            NormalMsg = true;
            abort = false;
        } else if (GlobalConfig->status != KVpncEnum::connected && msg.indexOf("check_control: control, cid =", 0, Qt::CaseInsensitive) > -1) {
            NormalMsg = true;
            // cid is greather than 0
            if (msg.section(',', 1, 1).section('=', 1, 1).trimmed() != "0") {             // check_control: control, cid = 17467, Ns = 2, Nr = 4
                GlobalConfig->appendLogEntry(QString("[l2tpd] " + i18n("L2TP tunnel to %1 established."  , QString(GlobalConfig->currentProfile->getGateway()))) , KVpncEnum::success);

                abort = false;
                connectSuccess = true;
            }
        } else if (msg.indexOf("Connecting to host", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry(QString("[l2tpd] " + i18n("L2TP connection to %1 established."  , QString(GlobalConfig->currentProfile->getGateway()))) , KVpncEnum::success);
            abort = false;
            if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists()) {
                GlobalConfig->appendLogEntry(QString("[l2tpd] " + i18n("L2TP tunnel to %1 established." , QString(GlobalConfig->currentProfile->getGateway()))) , KVpncEnum::success);

                abort = false;
            }
            connectSuccess = true;
        }

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

            GlobalConfig->status = KVpncEnum::connected;

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


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

            sleep(2);

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

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

        }


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

            if (GlobalConfig->currentProfile->getAuthMethod() == "chap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2") {
                // remove kvpnc entries from chap-secerets
                QFile ChapSecretsFile("/etc/ppp/chap-secrets");
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1", QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                if (ChapSecretsFile.open(QIODevice::ReadOnly)) {
                    QString chapsecret_content = "";
                    bool kvpnc_start_marker_found = false;
                    bool kvpnc_end_marker_found = false;
                    QStringList contentlist = QString(ChapSecretsFile.readAll()).split("\n");
                    for (int i = 0; i < contentlist.size(); ++i) {
                        QString line = contentlist.at(i);
                        if (line == "# --- generated by kvpnc. Do not edit it.") {
                            kvpnc_end_marker_found = true;
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("End marker in %1 found" , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                        }
                        if (line == "# +++ generated by kvpnc. Do not edit it.") {
                            kvpnc_start_marker_found = true;
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("Start marker in %1 found" , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                        }

                        if (kvpnc_start_marker_found == false) {
                            chapsecret_content += line;
                            chapsecret_content += '\n';
                        }
                    }
                    ChapSecretsFile.close();
                    if (ChapSecretsFile.remove()) {
                        if (GlobalConfig->KvpncDebugLevel > 2)
                            GlobalConfig->appendLogEntry(i18n("File %1 successfully removed" , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                        //        ChapSecretsFile.setName("/etc/ppp/chap-secrets2");
                        if (ChapSecretsFile.open(QIODevice::WriteOnly)) {
                            QTextStream stream(&ChapSecretsFile);
                            stream << chapsecret_content;
                            ChapSecretsFile.close();
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("File %1 successfully rewritten" , QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                        } else {
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("File %1 rewrite failed" , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
                        }
                    } else {
                        if (GlobalConfig->KvpncDebugLevel > 2)
                            GlobalConfig->appendLogEntry(i18n("File %1 remove failed" , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
                    }

                } else {
                    GlobalConfig->appendLogEntry(i18n("File %1 could not be opened." , QString("/etc/ppp/chap-secrets")), KVpncEnum::error);
                }
            }
            if (GlobalConfig->currentProfile->getAuthMethod() == "pap") {
                // remove kvpnc entries from pap-secerets
                QFile papSecretsFile("/etc/ppp/pap-secrets");
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1", QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
                if (papSecretsFile.open(QIODevice::ReadOnly)) {
                    QString papsecret_content = "";
                    bool kvpnc_start_marker_found = false;
                    bool kvpnc_end_marker_found = false;
                    QStringList contentlist = QString(papSecretsFile.readAll()).split("\n");
                    for (int i = 0; i < contentlist.size(); ++i) {
                        QString line = contentlist.at(i);
                        if (line == "# --- generated by kvpnc. Do not edit it.") {
                            kvpnc_end_marker_found = true;
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("End marker in %1 found" , QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
                        }
                        if (line == "# +++ generated by kvpnc. Do not edit it.") {
                            kvpnc_start_marker_found = true;
                            if (GlobalConfig->KvpncDebugLevel > 2)
                                GlobalConfig->appendLogEntry(i18n("Start marker in %1 found" , QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
                        }

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

                } else {
                    GlobalConfig->appendLogEntry(i18n("File %1 could not be opened." , QString("/etc/ppp/pap-secrets")), KVpncEnum::error);
                }
            }
            return ;
        }
    }
//   if (GlobalConfig->appPointer->hasPendingEvents ())
//    GlobalConfig->appPointer->processEvents();

}

void KVpnc::readFromStdout_openl2tp()
{
    QStringList msg_list = QString(OpenL2tpProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        bool abort = false;
        bool connectSuccess = false;

        if (GlobalConfig->enableDebugOpenl2tp) {
            GlobalConfig->appendLogEntry("[openl2tp] " + msg, KVpncEnum::debug);
        } else {
            if (msg.indexOf("FUNC:", 0, Qt::CaseInsensitive) < 0  && msg.indexOf("FSM:", 0, Qt::CaseInsensitive) < 0 && msg.indexOf("AVP:", 0, Qt::CaseInsensitive) < 0 && msg.indexOf("PROTO:", 0, Qt::CaseInsensitive) < 0 && msg.indexOf("XPRT:", 0, Qt::CaseInsensitive) < 0 && msg.indexOf("DATA:", 0, Qt::CaseInsensitive) < 0)
                GlobalConfig->appendLogEntry("[openl2tp] " + msg, KVpncEnum::debug);
        }

        if (msg.indexOf("address", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Got IP address"), KVpncEnum::debug);

            if (msg.indexOf("local", 0, Qt::CaseInsensitive) > -1) {
                TunnelInterfaceIP = msg.section(' ', 4, 4);
                if (!TunnelInterfaceIP.isEmpty())
                    GlobalConfig->appendLogEntry(i18n("Tunnel interface IP address: %1\n"  , QString(TunnelInterfaceIP)), KVpncEnum::debug);

                connectSuccess = true;
            }
        } else if (msg.indexOf("event ICRP_ACCEPT in state WAITREPLY", 0, Qt::CaseInsensitive) > -1) {
            // short before low level connection up
        } else if (msg.indexOf("starting UNIX pppd", 0, Qt::CaseInsensitive) > -1) {
            // low level connection sure up
        } else if (msg.indexOf("state change: WAITCTLREPLY --> ESTABLISHED", 0, Qt::CaseInsensitive) > -1) {
            // low level connection up
        } else if (msg.indexOf("Using interface", 0, Qt::CaseInsensitive) > -1) {

            L2tpPppDevice = msg.section(' ', 2, 2);
            if (GlobalConfig->KvpncDebugLevel >  2)
                GlobalConfig->appendLogEntry(i18n("Tunnel device: %1\n"  , QString(L2tpPppDevice)), KVpncEnum::debug);
        } else if (msg.indexOf("authentication succeeded:", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Authentication succeeded."), KVpncEnum::debug);
            abort = false;
//    connectSuccess=true;
        } else if (msg.indexOf("Connection terminated.", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Connection has been terminated."));
            GlobalConfig->appendLogEntry(i18n("Connection has been terminated."), KVpncEnum::info);
            abort = true;
        }



        if (connectSuccess) {

            sec = hour = min = 0;

            GlobalConfig->status = KVpncEnum::connected;

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


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

            sleep(2);

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

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

        }

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

            return ;
        }

    }
}

void KVpnc::readFromStderr_openl2tp()
{
    QStringList msg_list = QString(OpenL2tpProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        bool abort = false;
        GlobalConfig->appendLogEntry("[openl2tp err] " + msg, KVpncEnum::error);


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


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

            return ;
        }
    }
}

void KVpnc::readFromStdout_startstopOpenl2tp()
{
    QStringList msg_list = QString(StartStopOpenl2tpProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        bool abort = false;
        if (GlobalConfig->enableDebugOpenl2tp) {
            GlobalConfig->appendLogEntry("[openl2tp] " + msg, KVpncEnum::debug);
        } else {
            if (msg.indexOf("FUNC:", 0, Qt::CaseInsensitive) < 0  && msg.indexOf("FSM:", 0, Qt::CaseInsensitive) < 0 && msg.indexOf("AVP:", 0, Qt::CaseInsensitive) < 0 && msg.indexOf("PROTO:", 0, Qt::CaseInsensitive) < 0 && msg.indexOf("XPRT:", 0, Qt::CaseInsensitive) < 0 && msg.indexOf("DATA:", 0, Qt::CaseInsensitive) < 0)
                GlobalConfig->appendLogEntry("[openl2tp] " + msg, KVpncEnum::debug);
        }


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

            return ;
        }

    }
}

void KVpnc::readFromStderr_startstopOpenl2tp()
{
    QStringList msg_list = QString(StartStopOpenl2tpProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        GlobalConfig->appendLogEntry("[openl2tp err] " + msg, KVpncEnum::error);

        bool abort = false;
        if (abort) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("There is a reason to stop connecting, terminating \"%1\" process." , QString("openl2tp")) , KVpncEnum::debug);
            disconnectClicked();
            GlobalConfig->status = KVpncEnum::disconnected;
            setGuiStatus(KVpncEnum::disconnected);

            return ;
        }
    }
}

void KVpnc::readFromStdout_vtun()
{
    QStringList msg_list = QString(VtundProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        bool NormalMsg = true;
        bool ErrorMsg = false;
        bool abort = false;
        bool connectSuccess = false;



        /*
          if ( msg.indexOf ( "init_network: Unable to bind socket. Terminating", 0, Qt::CaseInsensitive ) > -1  )
         {

          }*/

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


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

        }
        // success
        if (connectSuccess) {

            sec = hour = min = 0;

            GlobalConfig->status = KVpncEnum::connected;

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


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

            sleep(2);

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

//    //FIXME make it better
//    PppdDevice = "ppp0";
//    NetworkInterface iface ( GlobalConfig, parent );
//    if ( iface.interfaceExist ( PppdDevice ) )
//    {
//     TunnelInterfaceIP = iface.getInterfaceIP ( PppdDevice );
//     GlobalConfig->appendLogEntry ( i18n ( "Tunnel device: %1\n"  , QString(PppdDevice )), KVpncEnum::debug );
//     if ( !TunnelInterfaceIP.isEmpty() )
//      GlobalConfig->appendLogEntry ( i18n ( "Tunnel interface IP address: %1\n"  , QString( TunnelInterfaceIP )), KVpncEnum::debug );
            // }


            if (GlobalConfig->currentProfile->getUseConnectionStatusCheck()) {
                startConnectionStatusCheck();
            }
        }
//   // normal
        if (NormalMsg) {
            if (GlobalConfig->KvpncDebugLevel > 1)
                GlobalConfig->appendLogEntry("[vtun] " + msg, KVpncEnum::debug);
        } else
//   if ( ErrorMsg )
        {
            GlobalConfig->appendLogEntry("[vtun err] " + msg, KVpncEnum::error);
        }
    }
}

void KVpnc::readFromStderr_vtun()
{
    QStringList msg_list = QString(VtundProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        bool NormalMsg = true;
        bool ErrorMsg = false;
        bool abort = false;
        bool connectSuccess = false;

        if (msg.indexOf("Session ", 0, Qt::CaseInsensitive) > -1 && msg.indexOf("opened", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->KvpncDebugLevel > 1)
                GlobalConfig->appendLogEntry(i18n("Session opened."), KVpncEnum::debug);
        }
        if (msg.indexOf("compression ", 0, Qt::CaseInsensitive) > -1 && msg.indexOf("initialized", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->KvpncDebugLevel > 1)
                GlobalConfig->appendLogEntry(i18n("Compression initialized."), KVpncEnum::debug);
        }
        if (msg.indexOf("UDP ", 0, Qt::CaseInsensitive) > -1 && msg.indexOf("initialized", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->KvpncDebugLevel > 1)
                GlobalConfig->appendLogEntry(i18n("UDP initialized."), KVpncEnum::debug);
        }
        if (msg.indexOf("encryption ", 0, Qt::CaseInsensitive) > -1 && msg.indexOf("initialized", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->KvpncDebugLevel > 1)
                GlobalConfig->appendLogEntry(i18n("Encryption initialized."), KVpncEnum::debug);

            // FIXME only if encryption is activated (always!?)
            connectSuccess = true;
        }
        if (msg.indexOf("Connection refused(111)", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Connection refused."));
            GlobalConfig->appendLogEntry(i18n("Connection refused."), KVpncEnum::error);
            abort = true;
            ErrorMsg = true;
        }
        // //   if ( msg.indexOf(" Exit ",0, Qt::CaseInsensitive) > -1 )
// //   {
// //    GlobalConfig->appendLogEntry(i18n("%1 has been exited." , QString("vtund")),KVpncEnum::error);
// //    abort=true;
// //    ErrorMsg=true;
// //   }
        if (msg.indexOf("Connection denied by ", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry(i18n("Connection denied. Password wrong?"), KVpncEnum::error);
            abort = true;
            ErrorMsg = true;
        }
        if (msg.indexOf("Connection closed by other side", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry(i18n("Connection was closed by the remote host. Please check your settings."), KVpncEnum::error);
            abort = true;
            ErrorMsg = true;
        }
        if (msg.indexOf("syntax error", 0, Qt::CaseInsensitive) > -1 || msg.indexOf("No hosts defined", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Syntax error in config detected. Please report that to the KVpnc maintainer."));
            GlobalConfig->appendLogEntry(i18n("Syntax error in config detected. Please report that to the KVpnc maintainer."), KVpncEnum::error);
            abort = true;
            ErrorMsg = true;
        }
        if (msg.indexOf("allocate pseudo tty", 0, Qt::CaseInsensitive) > -1) {
            KMessageBox::error(this, i18n("Cannot allocate pseudo tty.\nPlease check that your kernel has LEGACY PTY=y or recompile patched vtun. You can get the patch for UNIX98 PTS here: %1" , QString(QString("http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=451931"))));
            GlobalConfig->appendLogEntry(i18n("Cannot allocate pseudo tty."), KVpncEnum::error);
            abort = true;
            ErrorMsg = true;
        }

//    else if ( GlobalConfig->status != KVpncEnum::connected && msg.indexOf ( "check_control: control, cid =", 0, Qt::CaseInsensitive ) > -1 )
//    {
//     NormalMsg=true;
//     // cid is greather than 0
//     if ( msg.section ( ',', 1, 1 ).section ( '=', 1, 1 ).trimmed() != "0" )       // check_control: control, cid = 17467, Ns = 2, Nr = 4
//     {
//      GlobalConfig->appendLogEntry ( QString ( "[l2tpd] " + i18n ( "L2TP tunnel to %1 established." , QString( GlobalConfig->currentProfile->getGateway() )) ) , KVpncEnum::success );
//
//      abort = false;
//      connectSuccess = true;
//     }
//    }


        // success
        if (connectSuccess) {

            GlobalConfig->appendLogEntry(i18n("Connection established."), KVpncEnum::success);

            sec = hour = min = 0;

            GlobalConfig->status = KVpncEnum::connected;

            disconnect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));
            connect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));
            durationTimer.start(1000);
            setGuiStatus(KVpncEnum::connected);
            connectSuccess = false;

            setFirewallAfterConnect();
            if (GlobalConfig->currentProfile->getExecuteCmdAfterConnect())
                executeCommandAfterConnect();

            if (GlobalConfig->currentProfile->getUseAdditionalNetworkRoutes() && !GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty()) {
                addAdditionalNetworkRoutes();
                // GlobalConfig->appendLogEntry( i18n( "Add additional network routes..." ), KVpncEnum::debug );
            } else {
                // GlobalConfig->appendLogEntry( i18n( "No additional routes to add." ), KVpncEnum::debug );
            }
            if (GlobalConfig->currentProfile->getUseConnectionStatusCheck()) {
                startConnectionStatusCheck();
            }
        }

//   // normal
        if (NormalMsg) {
            if (GlobalConfig->KvpncDebugLevel > 1)
                GlobalConfig->appendLogEntry("[vtun] " + msg, KVpncEnum::debug);
        } else
//   if ( ErrorMsg )
        {
            GlobalConfig->appendLogEntry("[vtun err] " + msg, KVpncEnum::error);
        }

        if (abort) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("There is a reason to stop connecting, terminating \"%1\" process." , QString("vtund")) , KVpncEnum::debug);
            disconnectClicked();
            GlobalConfig->status = KVpncEnum::disconnected;
            setGuiStatus(KVpncEnum::disconnected);
            return ;
        }
        GlobalConfig->appPointer->processEvents();
    }
}

void KVpnc::readFromStdout_ssh()
{
    if (GlobalConfig->KvpncDebugLevel > 4)
        GlobalConfig->appendLogEntry("readFromStdout_ssh", KVpncEnum::debug);
    if (SshProcess) {
        QStringList msg_list = QString(SshProcess->readAllStandardOutput()).split('\n');
        for (int i = 0; i < msg_list.size(); ++i) {
            QString msg = msg_list.at(i);
            handleOutputFrom_ssh(msg, OutputMsg::normal);
        }
    }
}

void KVpnc::readFromStderr_ssh()
{
    if (GlobalConfig->KvpncDebugLevel > 4)
        GlobalConfig->appendLogEntry("readFromStderr_ssh", KVpncEnum::debug);
    if (SshProcess) {
        QStringList msg_list = QString(SshProcess->readAllStandardError()).split('\n');
        for (int i = 0; i < msg_list.size(); ++i) {
            QString msg = msg_list.at(i);
            handleOutputFrom_ssh(msg, OutputMsg::error);
        }
    }
}

void KVpnc::readFromPty_ssh()
{
    //  GlobalConfig->appendLogEntry("readFromPty_ssh", KVpncEnum::debug);
    if (SshPty) {
        QStringList msg_list = QString(SshPty->readAll()).split('\n');
        for (int i = 0; i < msg_list.size(); ++i) {
            QString msg = msg_list.at(i);
            handleOutputFrom_ssh(msg, OutputMsg::pty);
        }
    }
}

void KVpnc::handleOutputFrom_ssh(QString msg, OutputMsg::MsgType type)
{
    bool ErrorMsg = false;
    bool abort = false;
    bool connectSuccess = false;


    if (type == OutputMsg::normal) {
        if (GlobalConfig->KvpncDebugLevel > 3) {
            GlobalConfig->appendLogEntry("[ssh] " + msg, KVpncEnum::debug);
        }
    } else if (type == OutputMsg::error)
        GlobalConfig->appendLogEntry("[ssh err] " + msg, KVpncEnum::debug);
    else if (type == OutputMsg::pty) {
        if (GlobalConfig->KvpncDebugLevel > 3) {
            GlobalConfig->appendLogEntry("[ssh pty] " + msg, KVpncEnum::debug);
        }
    }


    if (msg.indexOf("ssh_is_up", 0, Qt::CaseInsensitive) > -1) {
        GlobalConfig->appendLogEntry(i18n("SSH tunnel is now up") , KVpncEnum::info);
        connectSuccess = true;
    } else if (msg.indexOf("REMOTE HOST IDENTIFICATION HAS CHANGED!", 0, Qt::CaseInsensitive) > -1) {
        ErrorMsg = true;
        KMessageBox::error(this, i18n("Remote host identification has changed.")) ;
        GlobalConfig->appendLogEntry(i18n("Remote host identification has changed.")  , KVpncEnum::error);
        abort = false;
    } else if (msg.indexOf("Host key verification failed", 0, Qt::CaseInsensitive) > -1) {
        ErrorMsg = true;
        KMessageBox::error(this, i18n("Host key verification failed"));
        GlobalConfig->appendLogEntry(i18n("Host key verification failed") , KVpncEnum::error);
        abort = true;
    } else if (msg.indexOf("has changed and you have requested strict checking", 0, Qt::CaseInsensitive) > -1) {
        ErrorMsg = true;
        KMessageBox::error(this, i18n("Host key for %1 has changed and you have requested strict checking."  , QString(GlobalConfig->TmpGatewayIP)));
        GlobalConfig->appendLogEntry(i18n("Host key for %1 has changed and you have requested strict checking."  , QString(GlobalConfig->TmpGatewayIP)) , KVpncEnum::error);
        abort = true;
    } else if (msg.indexOf(": No route to host", 0, Qt::CaseInsensitive) > -1) {
        ErrorMsg = true;
        KMessageBox::error(this, i18n("No route to host %1"  , QString(GlobalConfig->TmpGatewayIP)));
        GlobalConfig->appendLogEntry(i18n("No route to host %1"  , QString(GlobalConfig->TmpGatewayIP)) , KVpncEnum::error);
        abort = true;
    } else if (msg.indexOf("Authentication succeeded", 0, Qt::CaseInsensitive) > -1) {
        ErrorMsg = false;
        //    KMessageBox::error ( this, i18n ( "Authentication succeeded" ) );
        GlobalConfig->appendLogEntry(i18n("Authentication succeeded") , KVpncEnum::info);
        //    abort = true;
    } else if (msg.indexOf("Remote: Failed to open the tunnel device.", 0, Qt::CaseInsensitive) > -1) {
        ErrorMsg = true;
        KMessageBox::error(this, i18n("Remote: Failed to open the tunnel device."));
        GlobalConfig->appendLogEntry(i18n("Remote: Failed to open the tunnel device."), KVpncEnum::error);
        abort = true;
    } else if (msg.indexOf("open failed: administratively prohibited: open failed", 0, Qt::CaseInsensitive) > -1) {
        ErrorMsg = true;
        KMessageBox::error(this, i18n("Action administratively prohibited"));
        GlobalConfig->appendLogEntry(i18n("Action administratively prohibited") , KVpncEnum::error);
        abort = true;
    } else if (msg.indexOf("Connection established.", 0, Qt::CaseInsensitive) > -1) {
        //    KMessageBox::error ( this, i18n ( "Low level connection to host %1 established."  , QString( GlobalConfig->TmpGatewayIP )));
        GlobalConfig->appendLogEntry(i18n("Low level connection to host %1 established." , QString(GlobalConfig->TmpGatewayIP)) , KVpncEnum::info);
    } else if (msg.indexOf("No more authentication methods to try.", 0, Qt::CaseInsensitive) > -1) {
        ErrorMsg = true;
        KMessageBox::error(this, i18n("No more authentication methods to try."));
        GlobalConfig->appendLogEntry(i18n("No more authentication methods to try.") , KVpncEnum::error);
        abort = true;
    } else if (msg.indexOf("Permission denied", 0, Qt::CaseInsensitive) > -1) {
        timer.stop();
        connectCounter = 0;
        //    disconnect ( &timer, SIGNAL ( timeout() ), this, SLOT ( slotConnectTimedOut() ) );
        KMessageBox::error(this, i18n("Authentication has failed."));
        GlobalConfig->appendLogEntry(i18n("Authentication has failed.") , KVpncEnum::error);
        //abort = true;
        AuthRetry = true;
        GlobalConfig->haveUserData = false;
        connectClicked();
    } else if (msg.indexOf("'s password:", 0, Qt::CaseInsensitive) > -1) {
        ErrorMsg = false;
        GlobalConfig->appendLogEntry(i18n("Password asked, send it...") , KVpncEnum::error);
        abort = false;
        SshPty->write(GlobalConfig->TmpPassword.toUtf8());
        SshPty->write("\n");
    }



    if (ErrorMsg)
        GlobalConfig->appendLogEntry("[ssh error] " + ProcessMsg_connect, KVpncEnum::error);
    else if (GlobalConfig->KvpncDebugLevel > 2)
        GlobalConfig->appendLogEntry("[ssh2] " + ProcessMsg_connect, KVpncEnum::info);

    if (abort) {
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("There is a reason to stop connecting, terminating \"%1\" process." , QString("ssh")) , KVpncEnum::debug);
        disconnectClicked();
        GlobalConfig->status = KVpncEnum::disconnected;
        setGuiStatus(KVpncEnum::disconnected);
        return ;
    }

    // success
    else if (connectSuccess) {
        sec = hour = min = 0;

        GlobalConfig->status = KVpncEnum::connected;

        disconnect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));
        connect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));
        durationTimer.start(1000);
        setGuiStatus(KVpncEnum::connected);
        connectSuccess = false;

        GlobalConfig->appendLogEntry(i18n("Connection established."), KVpncEnum::success);

        //    GlobalConfig->appendLogEntry( QString("connectstring: "+ProcessMsg_connect), KVpncEnum::debug );

        SshDevice = "";
        if (!PppdDevice.isEmpty())
            SshDevice = PppdDevice;
        else {
            if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tun")
                SshDevice = "tun0";
            else
                SshDevice = "tap0";
        }

        // write ssh.<profile>.up
        QFile sshupfile(tmpPath + "ssh." + GlobalConfig->currentProfile->getName() + ".up");
        QTextStream sshupstream(&sshupfile);
        if (sshupfile.open(QIODevice::WriteOnly)) {
            sshupstream <<  "#!" << GlobalConfig->InterpreterShell << "\n";
            sshupstream << "# generated by kvpnc. Do not edit it." << "\n";
            sshupstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
            sshupstream << "cat /etc/resolv.conf > " << tmpPath + "resolv.conf." + GlobalConfig->currentProfile->getName() << "\n";

            NetworkInterface iface(GlobalConfig , parent);

            /* update dns? */
            if (GlobalConfig->currentProfile->getUseDnsUpdate()) {
                sshupstream << "if [ -x /sbin/resolvconf ] ; then\n";
                sshupstream << " echo > /dev/null" << "\n";
                sshupstream << "else" << "\n";
                sshupstream << " echo \"# generated by kvpnc. Do not edit it.\" > /etc/resolv.conf" << "\n";
                sshupstream << "fi\n";
            } else {
                /* dont update dns */
            }

            sshupstream << "\n";
            if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tun")
                sshupstream << GlobalConfig->pathToIfconfig << " " + SshDevice + " " + GlobalConfig->currentProfile->getLocalVirtualIP() + " pointopoint " << GlobalConfig->currentProfile->getRemoteVirtualIP() << " up" << "\n";
            if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tap")
                sshupstream << GlobalConfig->pathToIfconfig << " " + SshDevice + " " + GlobalConfig->currentProfile->getLocalVirtualIP()  << " up" << "\n";

            TunnelInterfaceIP = iface.getInterfaceIP(SshDevice);
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry("[ssh] " + i18n("Tunnel IP: %1"  , QString(TunnelInterfaceIP)) , KVpncEnum::debug);

            QString resolvtemp = "";
            bool no_nameserver = true;
            /* update dns? */
            if (GlobalConfig->currentProfile->getUseDnsUpdate()) {
                sshupstream << "if [ -x /sbin/resolvconf ] ; then\n";
                sshupstream << " dev=$1\n";
                sshupstream << " if [ -z $dev ] ; then\n";
                if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tun")
                    sshupstream << "  dev=\"tun0\"\n";
                else
                    sshupstream << "  dev=\"tap0\"\n";
                sshupstream << "fi\n";
                if (!TmpDns1.isEmpty() || !TmpDns2.isEmpty()) {
                    no_nameserver = false;
                    sshupstream << "if [ -x /sbin/resolvconf ] ; then\n";
                    if (TmpDns2.isEmpty()) {
                        resolvtemp += "nameserver " + TmpDns1 + "\n";
                    } else {
                        resolvtemp += "nameserver " + TmpDns1 + "\nnameserver " + TmpDns2 + "\n";
                    }

                    sshupstream << "else" << "\n";
                    sshupstream << "  echo >> /etc/resolv.conf\n";
                    sshupstream << "  echo \"# generated by kvpnc. Do not edit it.\" > /etc/resolv.conf" << "\n";
                    sshupstream << "  echo \"# profile: " + GlobalConfig->currentProfile->getName() << "\" >> /etc/resolv.conf" << "\n";
                    sshupstream << "  echo \"nameserver " << TmpDns1 << "\" >> /etc/resolv.conf" << "\n";
                    if (!TmpDns2.isEmpty())
                        sshupstream << "  echo \"nameserver " << TmpDns2 << "\" >> /etc/resolv.conf" << "\n";

                }

                sshupstream << "fi" << "\n";

                sshupstream << "# " << "\n";

                if ((GlobalConfig->currentProfile->getUseDnsServer() && !GlobalConfig->currentProfile->getDnsServer().isEmpty()) || (GlobalConfig->currentProfile->getUseSearchDomainInResolvConf()  && ! !GlobalConfig->currentProfile->getSearchDomainInResolvConf().isEmpty())) {
                    sshupstream << "if [  -x /sbin/resolvconf ] ; then\n";
                    sshupstream << " dev=$1\n";
                    sshupstream << " if [ -z $dev ] ; then\n";
                    if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tun")
                        sshupstream << "  dev=\"tun0\"\n";
                    else
                        sshupstream << "  dev=\"tap0\"\n";
                    sshupstream << " fi\n";

                    if (GlobalConfig->currentProfile->getUseDnsServer() && !GlobalConfig->currentProfile->getDnsServer().isEmpty())
                        resolvtemp += "nameserver " + GlobalConfig->currentProfile->getDnsServer() + "\n";
                    if (GlobalConfig->currentProfile->getUseSearchDomainInResolvConf() && !GlobalConfig->currentProfile->getSearchDomainInResolvConf().isEmpty())
                        resolvtemp += "search " + GlobalConfig->currentProfile->getSearchDomainInResolvConf() + "\n";
                    sshupstream << "else\n";
                    if (GlobalConfig->currentProfile->getUseDnsServer() && !GlobalConfig->currentProfile->getDnsServer().isEmpty()) {
                        sshupstream << "  echo \"nameserver " << GlobalConfig->currentProfile->getDnsServer() + "\" >> /etc/resolv.conf\n";
                        no_nameserver = false;
                    }
                    if (GlobalConfig->currentProfile->getUseSearchDomainInResolvConf() && !GlobalConfig->currentProfile->getSearchDomainInResolvConf().isEmpty())
                        sshupstream << "  echo \"search " << GlobalConfig->currentProfile->getSearchDomainInResolvConf() + "\" >> /etc/resolv.conf\n";
                    sshupstream << "fi\n";
                }


                sshupstream << "if [ -x /sbin/resolvconf ] ; then\n";
                sshupstream << "  echo \"" + resolvtemp + "\" > " + tmpPath + "resolvconf." + GlobalConfig->currentProfile->getName() << "\n";
                if (no_nameserver == true) {
                    sshupstream << "   cat   " + tmpPath + "/resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() + " | grep nameserver >> " + tmpPath + "/pppd.resolvconf.tmp" + "\n";
                }

                sshupstream << "  cat   " + tmpPath + "resolvconf." + GlobalConfig->currentProfile->getName()+ " | /sbin/resolvconf -a $dev\n";

                /* crissi: -u seems not nessary */
                //sshupstream << " cat   " + tmpPath + "/pppd.resolvconf.tmp | /sbin/resolvconf -u\n";

                if (!GlobalConfig->holdGeneratedScripts)
                    sshupstream << "  rm -f   " + tmpPath + "resolvconf." + GlobalConfig->currentProfile->getName()+"\n";

                if (no_nameserver == true) {
                    sshupstream << "else\n";
                    sshupstream << "  cat " << tmpPath + "/resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName() + " | grep nameserver >> /etc/resolv.conf\n";
                }

                sshupstream << "fi\n";
                //                sshupstream << "chmod u-w  /etc/resolv.conf\n";

            } else {
                /* dont update dns */
            }
            sshupstream << GlobalConfig->pathToIp << " route show | grep default > " << OldDefaultroute << "\n";

            if (GlobalConfig->currentProfile->getReplaceDefaultRoute()) {
                sshupstream << GlobalConfig->pathToIp + " route replace default dev " + SshDevice + "\n";

                if (GlobalConfig->KvpncDebugLevel > 3)
                    GlobalConfig->appendLogEntry(i18n("Setting extra route: %1 over %2 gw %3"  , QString(GlobalConfig->currentProfile->getGateway()), GlobalConfig->OldDefaultDev, GlobalConfig->OldDefaultGw), KVpncEnum::debug);

                sshupstream << GlobalConfig->pathToIp + " route add " + GlobalConfig->currentProfile->getGateway() + "/32 via " << GlobalConfig->OldDefaultGw << " dev " << GlobalConfig->OldDefaultDev << "\n";

            }
            //     NetworkInterface iface(GlobalConfig , parent);
            GlobalConfig->NewDefaultGw = iface.getGatewayOfDefaultInterface();

            if (GlobalConfig->NewDefaultGw != "0.0.0.0") {
                if (GlobalConfig->KvpncDebugLevel > 3)
                    GlobalConfig->appendLogEntry(i18n("Setting extra route: %1 over %2 gw %3"  , QString("0.0.0.0"), SshDevice , GlobalConfig->NewDefaultGw), KVpncEnum::debug);
                sshupstream << GlobalConfig->pathToIp + " route add 0.0.0.0 via " << GlobalConfig->NewDefaultGw << " dev " << SshDevice << "\n";
            }
            sshupfile.close();
        }


        QProcess SshUpProcess(this);
        QString proc = GlobalConfig->InterpreterShell;
        QStringList args;
        args.append(tmpPath + "ssh." + GlobalConfig->currentProfile->getName() + ".up");
        SshUpProcess.setEnvironment(*env);
        SshUpProcess.start(proc, args);
        if (!SshUpProcess.waitForStarted()) {
            KMessageBox::sorry(this, i18n("\"%1\" (%2) start failed."  , QString("SshUpScript")  , QString(tmpPath + "ssh." + GlobalConfig->currentProfile->getName() + ".up")));
        } else {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("\"%1\" (%2) started."  , QString("SshUpScript"), QString((tmpPath + "ssh." + GlobalConfig->currentProfile->getName() + ".up"))), KVpncEnum::debug);
            waitForFinished(&SshUpProcess, 100);


            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("\"%1\" (%2) finished."  , QString("SshUpScript"), QString(tmpPath + "ssh." + GlobalConfig->currentProfile->getName() + ".up")) , KVpncEnum::debug);
        }

        setFirewallAfterConnect();
        if (GlobalConfig->currentProfile->getExecuteCmdAfterConnect())
            executeCommandAfterConnect();

        if (GlobalConfig->currentProfile->getReplaceDefaultRoute()) {
            tmpPath = KStandardDirs::locateLocal("data", "kvpnc/");
            QString SshReplaceDefaultRouteScript = tmpPath + "ssh_replace_defaultroute." + GlobalConfig->currentProfile->getName() + ".sh";

            QFile file(SshReplaceDefaultRouteScript);
            QTextStream stream(&file);
            if (file.open(QIODevice::WriteOnly)) {
                stream << "# generated by kvpnc. Do not edit it." << "\n";
                stream << "\n";
                file.close();
                QProcess ReplaceDefaultRouteProcess(this);
                QString proc = GlobalConfig->InterpreterShell;
                QStringList args;
                args.append(SshReplaceDefaultRouteScript);
                ReplaceDefaultRouteProcess.setEnvironment(*env);
                ReplaceDefaultRouteProcess.start(proc, args);
                if (!ReplaceDefaultRouteProcess.waitForStarted()) {
                    KMessageBox::sorry(this, i18n("\"%1\" %2 start failed."  , QString(i18n("ssh replace route process")), QString((tmpPath + "pppd_replace_defaultroute." + GlobalConfig->currentProfile->getName() + ".sh"))));
                    //    disconnectClicked();
                    //    setGuiStatus(KVpncEnum::disconnected);
                } else {
                    if (GlobalConfig->KvpncDebugLevel > 1)
                        GlobalConfig->appendLogEntry(i18n("\"%1\" (%2) started."  , QString(i18n("ssh replace route process")) , QString((tmpPath + "ssh_replace_defaultroute." + GlobalConfig->currentProfile->getName() + ".sh"))) , KVpncEnum::debug);

                    waitForFinished(&ReplaceDefaultRouteProcess, 100);

                    if (GlobalConfig->KvpncDebugLevel > 1)
                        GlobalConfig->appendLogEntry(i18n("\"%1\" (%2) finished.", i18n("ssh replace route process"), tmpPath + "ssh_replace_defaultroute." + GlobalConfig->currentProfile->getName() + ".sh") , KVpncEnum::debug);
                }

            } else {
                GlobalConfig->appendLogEntry(i18n("Could not write: \"%1\" (%2)." , QString(i18n("ssh replace route script")), SshReplaceDefaultRouteScript), KVpncEnum::error);
            }
        }
        {

            if (GlobalConfig->currentProfile->getUseAdditionalNetworkRoutes() && !GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty())
                addAdditionalNetworkRoutes();

            if (GlobalConfig->currentProfile->getUseConnectionStatusCheck()) {
                startConnectionStatusCheck();
            }
        }
    }

}

void KVpnc::readFromStdout_ping()
{
    //KNotification *notification = new KNotification("ping result",
    //topLevelWidget());

    QStringList msg_list = QString(PingProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString ProcessMsg_connect = msg_list.at(i);

        //mw->DebugOutput->append( "raw out (pingtest): " + ProcessMsg_connect );

        if (ProcessMsg_connect.indexOf("time=", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry("[ping] " + ProcessMsg_connect, KVpncEnum::success);
            //  notification->setText(i18n("Ping has succeeded."));
            //  notification->sendEvent();
        } else if (ProcessMsg_connect.indexOf("100 % packet loss", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry("[ping err] " + ProcessMsg_connect, KVpncEnum::error);
            //  notification->setText(i18n("Ping has failed."));
            //  notification->sendEvent();
        } else {
            if (ProcessMsg_connect.indexOf("failed to bind", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("Binding interface failed."));
                GlobalConfig->appendLogEntry(i18n("Binding interface failed.") , KVpncEnum::error);
            } else if (ProcessMsg_connect.indexOf("Destination Host Unreachable", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("Destination host is unreachable."));
                GlobalConfig->appendLogEntry(i18n("Destination host is unreachable.") , KVpncEnum::error);
            }

            if (GlobalConfig->KvpncDebugLevel > 3)
                GlobalConfig->appendLogEntry("[ping]: " + ProcessMsg_connect, KVpncEnum::debug);
        }
    }
}

void KVpnc::readFromStderr_ping()
{
    QStringList msg_list = QString(PingProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString ProcessMsg_connect = msg_list.at(i);

        //mw->DebugOutput->append( "raw err (pingtest): " + ProcessMsg_connect );
        if (ProcessMsg_connect.indexOf("time=", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry("[ping] " + ProcessMsg_connect, KVpncEnum::success);
        } else if (ProcessMsg_connect.indexOf("100 % packet loss", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry("[ping err] " + ProcessMsg_connect, KVpncEnum::error);
        } else {
            if (ProcessMsg_connect.indexOf("failed to bind", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("Binding interface failed."));
                GlobalConfig->appendLogEntry(i18n("Binding interface failed.") , KVpncEnum::error);
            }
            if (ProcessMsg_connect.indexOf("Destination Host Unreachable", 0, Qt::CaseInsensitive) > -1) {
                KMessageBox::error(this, i18n("Destination host is unreachable."));
                GlobalConfig->appendLogEntry(i18n("Destination host is unreachable.") , KVpncEnum::error);
            }
        }
    }
}

void KVpnc::readFromStdout_route()
{
    QStringList msg_list = QString(RouteProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("[route] " + msg, KVpncEnum::debug);

    }
}

void KVpnc::readFromStderr_route()
{
    QStringList msg_list = QString(RouteProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("[route err] " + msg, KVpncEnum::debug);

    }
}

void KVpnc::readFromStdout_disconnect()
{
    QStringList msg_list = QString(DisconnectProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("[disconnect] " + msg, KVpncEnum::debug);

    }
}

void KVpnc::readFromStderr_disconnect()
{
    QStringList msg_list = QString(DisconnectProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("[disconnect err] " + msg, KVpncEnum::error);
    }
}

void KVpnc::readFromStdout_setVirtualIP()
{
    QStringList msg_list = QString(SetVirtualIPProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(msg, KVpncEnum::debug);
    }
}

void KVpnc::readFromStderr_setVirtualIP()
{
    QStringList msg_list = QString(SetVirtualIPProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        GlobalConfig->appendLogEntry(msg, KVpncEnum::error);
        setVirtualIPSuccess = false;
    }
}

void KVpnc::readFromStdout_connectionStatusCheck()
{
    QStringList msg_list = QString(ConnectionStatusCheckProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        if (msg.indexOf("PING ok.", 0, Qt::CaseInsensitive) > -1) {
            /* Connection alive */
            if (GlobalConfig->KvpncDebugLevel > 0) {
                if (GlobalConfig->currentProfile->getDoPingIP()) {
                    GlobalConfig->appendLogEntry(i18n("Ping to %1 within %2 checks every %3s was ok."  , QString(GlobalConfig->currentProfile->getPingHostIP()), GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount() , GlobalConfig->currentProfile->getConnectionStatusInterval()), KVpncEnum::debug);
                } else {
                    GlobalConfig->appendLogEntry(i18n("Ping to %1 within %2 checks every %3s was ok."  , QString(GlobalConfig->currentProfile->getGateway()), GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount() , GlobalConfig->currentProfile->getConnectionStatusInterval()), KVpncEnum::debug);
                }
            }
        }
        if (msg.indexOf("PING failed!", 0, Qt::CaseInsensitive) > -1) {
            /* Connection dead?! */
            if (GlobalConfig->KvpncDebugLevel > 0) {
                if (GlobalConfig->currentProfile->getDoPingIP()) {
                    GlobalConfig->appendLogEntry(i18n("Ping to %1 within %2 checks every %3s has failed." , QString(GlobalConfig->currentProfile->getPingHostIP()), GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount() , GlobalConfig->currentProfile->getConnectionStatusInterval()), KVpncEnum::error);
//    notification->setText(i18n("Ping to %1 within %2 checks every %3s has failed.",
//       QString(GlobalConfig->currentProfile->getPingHostIP()),
//       GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount(),
//       GlobalConfig->currentProfile->getConnectionStatusInterval()));
//    notification->sendEvent();
                } else {
                    GlobalConfig->appendLogEntry(i18n("Ping to %1 within %2 checks every %3s has failed."  , QString(GlobalConfig->currentProfile->getGateway()), GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount() , GlobalConfig->currentProfile->getConnectionStatusInterval()), KVpncEnum::error);
//    notification->setText(i18n("Ping to %1 within %2 checks every %3s has failed.",
//       QString(GlobalConfig->currentProfile->getGateway()),
//       GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount(),
//       GlobalConfig->currentProfile->getConnectionStatusInterval()));
//    notification->sendEvent();
                }
            }
            disconnect(ConnectionStatusCheckProcess, SIGNAL(readyReadStdout()), this, SLOT(readFromStdout_connectionStatusCheck()));
            disconnect(ConnectionStatusCheckProcess, SIGNAL(readyReadStderr()), this, SLOT(readFromStderr_connectionStatusCheck()));
            ConnectionStatusCheckProcess->kill();
            // kill connection
            disconnectClicked();

            if (GlobalConfig->currentProfile->getDoReconnectAfterConnectionLost()) {
                if (GlobalConfig->currentProfile->getUseReconnectDelay()) {
                    GlobalConfig->appendLogEntry(i18n("Waiting %1s for reconnect..."  , QString(GlobalConfig->currentProfile->getReconnectDelay())), KVpncEnum::info);
                    for (int time = 0; time <= GlobalConfig->currentProfile->getReconnectDelay() * 1000; time += 200) {
                        usleep(200);
                        GlobalConfig->appPointer->processEvents();
                    }
                }
                //   if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Reconnect after connection lost enabled, reconnecting..."), KVpncEnum::info);
                connectClicked();
            }
        }

    }
}

void KVpnc::readFromStderr_connectionStatusCheck()
{
    QStringList msg_list = QString(ConnectionStatusCheckProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        //  if ( msg.indexOf( "PING ok.", 0, Qt::CaseInsensitive ) > -1 )
        //  {
        //   /* Connection alive */
        //   if (GlobalConfig->KvpncDebugLevel > 0)
        //    GlobalConfig->appendLogEntry ( i18n("Ping to %1 within %2 checks every %3s was ok." , QString(GlobalConfig->currentProfile->getGateway()) , QString(GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount()),GlobalConfig->currentProfile->getConnectionStatusInterval())), KVpncEnum::debug );
        //
        //  }
        //  if ( msg.indexOf( "PING failed!", 0, Qt::CaseInsensitive ) > -1 )
        //  {
        //   /* Connection dead?! */
        //   if (GlobalConfig->KvpncDebugLevel > 0)
        //    GlobalConfig->appendLogEntry ( i18n("Ping to %1 within %2 checks every %3s was ok. , QString(GlobalConfig->currentProfile->getGateway()), GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount(), GlobalConfig->currentProfile->getConnectionStatusInterval() ), KVpncEnum::error );

//   notification->setText(i18n("Ping to %1 within %2 checks every %3s was ok.",
//      QString(GlobalConfig->currentProfile->getGateway()),
//      GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount(),
//      GlobalConfig->currentProfile->getConnectionStatusInterval()));
//   notification->sendEvent();

        //   // kill connection
        //   disconnectClicked();
        //  }
    }
}

void KVpnc::readFromStdout_executeCommandBeforeConnect()
{
    QStringList msg_list = QString(CmdBeforeConnectProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        if (GlobalConfig->KvpncDebugLevel > 1)
            GlobalConfig->appendLogEntry("[CmdBeforeConnect] " + msg, KVpncEnum::debug);
    }
}

void KVpnc::readFromStderr_executeCommandBeforeConnect()
{
    QStringList msg_list = QString(CmdBeforeConnectProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        GlobalConfig->appendLogEntry("[CmdBeforeConnect err] " + msg, KVpncEnum::error);
    }
}

void KVpnc::readFromStdout_executeCommandAfterConnect()
{
    QStringList msg_list = QString(CmdAfterConnectedProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        if (GlobalConfig->KvpncDebugLevel > 1)
            GlobalConfig->appendLogEntry("[CmdAfterConnect] " + msg, KVpncEnum::debug);
    }
}

void KVpnc::readFromStderr_executeCommandAfterConnect()
{
    QStringList msg_list = QString(CmdAfterConnectedProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        GlobalConfig->appendLogEntry("[CmdAfterConnect err] " + ProcessMsg_connect, KVpncEnum::error);
    }
}

void KVpnc::readFromStdout_executeCommandBeforeDisconnect()
{
    QStringList msg_list = QString(CmdBeforeDisconnectProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        if (GlobalConfig->KvpncDebugLevel > 1)
            GlobalConfig->appendLogEntry("[CmdBeforeDisconnect] " + msg, KVpncEnum::debug);
    }
}

void KVpnc::readFromStderr_executeCommandBeforeDisconnect()
{
    QStringList msg_list = QString(CmdBeforeDisconnectProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        GlobalConfig->appendLogEntry("[CmdBeforeDisconnect err] " + msg, KVpncEnum::error);
    }
}

void KVpnc::readFromStdout_executeCommandAfterDisconnect()
{
    QStringList msg_list = QString(CmdAfterDisconnectedProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        if (GlobalConfig->KvpncDebugLevel > 1)
            GlobalConfig->appendLogEntry("[CmdAfterDisconnect] " + msg, KVpncEnum::debug);
    }
}

void KVpnc::readFromStderr_executeCommandAfterDisconnect()
{
    QStringList msg_list = QString(CmdAfterDisconnectedProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        GlobalConfig->appendLogEntry("[CmdAfterDisconnect err] " + msg, KVpncEnum::error);
    }
}

void KVpnc::readCiscoVpncTestProcessOutput()
{
    QStringList msg_list = QString(TestCiscoVpncProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);

        if (GlobalConfig->KvpncDebugLevel > 3)
            GlobalConfig->appendLogEntry(i18n("msg: %1"  , QString(msg)), KVpncEnum::debug);

        if (msg == "")
            return ;
        if (msg.indexOf("The VPN module is not loaded.", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->KvpncDebugLevel > 1)
                GlobalConfig->appendLogEntry(i18n("Virtual interface of cisco client is not present"), KVpncEnum::debug);
            ciscoVpncRunning = false;
            return;
        } else if (msg.indexOf("cisco_ipsec", 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->KvpncDebugLevel > 1)
                GlobalConfig->appendLogEntry(i18n("Virtual interface of cisco client is present"), KVpncEnum::debug);
            ciscoVpncRunning = true;
            return;
        }
    }
}

void KVpnc::terminateConnection(QProcess *proc)
{
    if (proc->state() == QProcess::Running) {
//         proc->terminate();
//         proc->terminate();
//         proc->terminate();

        //  QTimers::singleShot( 5000, proc, SLOT( kill() ) );

    }
    timer.stop();
    durationTimer.stop();
    GlobalConfig->status = KVpncEnum::disconnected;
    connectCounter = 0;
    setGuiStatus(KVpncEnum::disconnected);

}

void KVpnc::connectionEnded()
{
    durationTimer.stop();
    GlobalConfig->status = KVpncEnum::disconnected;

    if (prevConnectionState == 1)    //connecting
        GlobalConfig->appendLogEntry(i18n("Successful connect try canceled.") , KVpncEnum::success);
    else
        GlobalConfig->appendLogEntry(i18n("Successful disconnected.") , KVpncEnum::success);


    // clean up scripts
    if (!GlobalConfig->holdGeneratedScripts) {

        if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco) {

        }

        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig) {
            QFile file(QString("/etc/opt/cisco-vpnclient/Profiles/") + QString("kvpnc_") + QString(GlobalConfig->currentProfile->getName() + ".pcf"));
            file.remove();
        }

        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon) {
            QFile file(tmpPath + "setkey." + GlobalConfig->currentProfile->getName() + ".conf");
            file.remove();
            file.setFileName(tmpPath + "/setkey." + GlobalConfig->currentProfile->getName() + ".sh");
            file.remove();
            file.setFileName(tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".conf");
            file.remove();
            file.setFileName(tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".add_racoon.sh");
            file.remove();
            file.setFileName(tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".remove_racoon.sh");
            file.remove();
            file.setFileName(tmpPath + "setkey." + GlobalConfig->currentProfile->getName() + ".remove_setkey.sh");
            file.remove();

            if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk) {
                file.setFileName(tmpPath + "psk." + GlobalConfig->currentProfile->getName() + ".key");
                file.remove();
            }
            file.setFileName(tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log");
            file.remove();
        } // racoon

        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan) {
            QFile file(tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".add_ipsec_freeswan.sh");
            file.remove();
            file.setFileName(tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".remove_ipsec_freeswan.sh");
            file.remove();

        } // freeswan

        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp) {

        }

        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn) {

        }

    }

    if (prevConnectionState != 1) {  // connected
        QString durationString(i18n("%1:%2:%3"  , QString(QString().sprintf("%02u", hour)), QString().sprintf("%02u", min) , QString().sprintf("%02u", sec)));
        GlobalConfig->appendLogEntry(i18n("Connection duration was %1 hours, %2 minutes, %3 seconds"  , QString(QString().sprintf("%02u", hour)), QString().sprintf("%02u", min) , QString().sprintf("%02u", sec)), KVpncEnum::info);
    }
    connectCounter = 0;
    GlobalConfig->TmpPassword = "";
    GlobalConfig->TmpGroupPassword = "";
}

void KVpnc::slotConnectTimedOut()
{
    this->connectCounter++;

    if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig) {
        if (connectCounter > GlobalConfig->connectSleepRetry && timer.isActive()) {
            timer.stop();
            // it does not get it connected so we kill it :)

            GlobalConfig->appendLogEntry(i18n("Timeout while connecting to %1. %2 connect process will be killed."  , QString(GlobalConfig->currentProfile->getGateway()), QString("vpnc")), KVpncEnum::error);

            if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco) {
                if (VpncProcess != 0 && VpncProcess->state() == QProcess::Running)
                    VpncProcess->kill();
            }
            if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig) {
                if (CiscoVpncProcess != 0 && CiscoVpncProcess->state() == KProcess::Running)
                    CiscoVpncProcess->kill();
            }

            GlobalConfig->status = KVpncEnum::disconnected;
            mw->buttonConnect->setEnabled(true);
            mw->buttonDisconnect->setEnabled(false);
            this->ConnectAction->setEnabled(true);
            this->DisconnectAction->setEnabled(false);
            //parent->statusBar() ->insertItem( i18n( "Connected" ), 2, 0, true );
            KVpncDock->setStatus(KVpncEnum::disconnected);
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Connection failed (timeout)."), KVpncEnum::debug);
            disconnectClicked();
            slotStatusMsg(i18n("Timeout while connecting to %1. %2 connect process will be killed." , QString(GlobalConfig->currentProfile->getGateway()) , QString("vpnc")), ID_FLASH_MSG);
            slotStatusMsg(i18n("Disconnected"), ID_CONNECTION_MSG);
            KVpncDock->setToolTip(i18n("Disconnected"));
            connectCounter = 0;
            setGuiStatus(KVpncEnum::disconnected);
            KMessageBox::error(this, i18n("Timeout while connecting to %1 (%2) after %3s. Please check if the VPN server is reachable and the settings (UDP/TCP, local port, UDP encapsulation port) are correct. Maybe the timeout must be increased too."  , QString(GlobalConfig->currentProfile->getGateway()), GlobalConfig->currentProfile->getName() , GlobalConfig->tryConnectTimeout));
        } else if (GlobalConfig->currentProfile->getDoReconnectAfterConnectionLost()) {
            GlobalConfig->appendLogEntry(i18np("Waiting 1 second before connecting...", "Waiting %1 seconds before connecting..." , GlobalConfig->connectSleepDelay), KVpncEnum::info);
            slotStatusMsg(i18n("Waiting for connect..."), ID_FLASH_MSG);
        }
    } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan ||  GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
        timer.stop();
        GlobalConfig->appendLogEntry(i18n("Timeout while connecting to %1. %2 connect process will be killed." , QString(GlobalConfig->currentProfile->getGateway()) , QString("ipsec")), KVpncEnum::error);

        disconnectClicked();

    }
}

void KVpnc::newSessionClicked()
{
    // call new profile dialog...
    NewProfileDialog newdlg(parent, this, i18n("New Profile"), GlobalConfig);
    newdlg.exec();
    if (newdlg.newProfileCreated) {
        bool nameOk = false;
        bool ok;
        QString newName=newdlg.getName();
        QString Oldname =  newdlg.getName();
        while ( nameOk == false )
        {
            for (int accountIdx = 0; accountIdx < GlobalConfig->AccountList->size(); ++accountIdx) {
                VpnAccountData *it = GlobalConfig->AccountList->at(accountIdx);
                if ( ( it != GlobalConfig->currentProfile ) && ( it->getName() == newName ) )
                {
                    //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 ( this, i18n ( "Profile name exists." ), i18n ( "Name Exists" ) );

                    newName = KInputDialog::getText ( i18n ( "New Name" ), i18n ( "New name for profile:" ), QString ( Oldname + "_2" ), &ok );
                    if ( ok == false )
                    {
                        KMessageBox::information ( 0, i18n ( "Renaming the newly created profile was canceled." ) );
                        GlobalConfig->appendLogEntry ( i18n ( "Renaming the newly created profile was canceled." ), KVpncEnum::info );
                        slotStatusMsg ( i18n ( "Renaming the newly created profile was canceled." ), ID_FLASH_MSG );
                        return ;
                    }
                }
            }
            if ( newName.isEmpty() )
                nameOk=false;
            else
                nameOk = true;
        }

        if (nameOk)
        {
            profileAddedOrDeleted();
            mw->SessionCombo->setCurrentItem(newdlg.getName());

            mw->SessionCombo->setEnabled(true);
            DeleteSessionAction->setEnabled(true);
            SaveSessionAction->setEnabled(true);
            ImportSessionAction->setEnabled(true);
            ConnectAction->setEnabled(true);
            mw->buttonConnect->setEnabled(true);

            sessionToggled(newdlg.getName());

            slotStatusMsg(i18n("Profile \"%1\" added."  , QString(mw->SessionCombo->currentText())), ID_FLASH_MSG);
            GlobalConfig->appendLogEntry(i18n("Profile \"%1\" added."  , QString(mw->SessionCombo->currentText())) , KVpncEnum::info);
            GlobalConfig->saveOptions();
            saveGuiOptions();

            QuickConnectMenu->clear();
            for (int accountIdx = 0; accountIdx < GlobalConfig->AccountList->size(); ++accountIdx) {
                VpnAccountData *it = GlobalConfig->AccountList->at(accountIdx);
                kDebug() << "item: " << it->getName() << endl;
                QuickConnectMenu->addAction(it->getName());
                mw->SessionCombo->insertItem(accountIdx, it->getName());
            }
            mw->SessionCombo->model()->sort(0);
            GlobalConfig->currentProfile = GlobalConfig->AccountList->first();
            mw->SessionCombo->setEnabled(true);
            mw->buttonConnect->setEnabled(true);
            this->sessionToggled(GlobalConfig->currentProfile->getName());

        } else {
            GlobalConfig->appendLogEntry ( i18n ( "Renaming the newly created profile was canceled." ), KVpncEnum::info );
            slotStatusMsg ( i18n ( "Creating new profile canceled." ), ID_FLASH_MSG );
            GlobalConfig->appendLogEntry ( i18n ( "Creating new profile canceled." ), KVpncEnum::info );
        }
    } else {
        slotStatusMsg(i18n("Creating new profile canceled."), ID_FLASH_MSG);
        GlobalConfig->appendLogEntry(i18n("Creating new profile canceled."), KVpncEnum::info);
        GlobalConfig->appendLogEntry ( i18n ( "Renaming the newly created profile was canceled." ), KVpncEnum::info );
        slotStatusMsg ( i18n ( "Creating new profile canceled." ), ID_FLASH_MSG );
        GlobalConfig->appendLogEntry ( i18n ( "Creating new profile canceled." ), KVpncEnum::info );
    }
}

void KVpnc::saveSessionClicked()
{
    GlobalConfig->appPointer->setOverrideCursor(QCursor(Qt::WaitCursor));
    if (!GlobalConfig->AccountList->isEmpty()) {
        QString Name=GlobalConfig->currentProfile->getName();
        GlobalConfig->appendLogEntry(i18n("Saving profile %1...", Name), KVpncEnum::info);
        this->slotStatusMsg(i18n("Saving profile %1...", Name), ID_STATUS_MSG);
        GlobalConfig->saveOptions(true, Name);
        GlobalConfig->appendLogEntry(i18n("Profile %1 saved.", Name), KVpncEnum::info);
        this->slotStatusMsg(i18n("Profile %1 saved.", Name), ID_FLASH_MSG);
    }
    this->slotStatusMsg(i18n("Ready."), ID_STATUS_MSG);
    GlobalConfig->appPointer->restoreOverrideCursor();
}

void KVpnc::deleteSessionClicked()
{
    if (GlobalConfig->currentProfile == 0)
        return ;

    QString Name = GlobalConfig->currentProfile->getName();

    ToolInfo *IpsecToolInfo = Utils(GlobalConfig).getToolInfo("ipsec") ;

    QString TypeString = i18n("unknown");
    if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco)
        TypeString =  i18n("Cisco");
    else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig)
        TypeString =  i18n("Cisco (proprietary)");
    else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp)
        TypeString =  i18n("PPTP");
    else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan) {
        if (IpsecToolInfo->Version.contains("Openswan", Qt::CaseInsensitive))
            IpsecType = TypeString =  i18n("Openswan");
        else if (IpsecToolInfo->Version.contains("strongSwan", Qt::CaseInsensitive))
            IpsecType = TypeString =  i18n("strongSwan");
        else
            IpsecType = TypeString =  i18n("FreeS/WAN");
    } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon)
        TypeString = "racoon";
    else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn)
        TypeString = "OpenVPN";
    else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon) {
        TypeString = "L2TP (racoon)";
    } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
        if (IpsecToolInfo->Version.contains("Openswan", Qt::CaseInsensitive))
            IpsecType = TypeString = "L2TP (Openswan)";
        else if (IpsecToolInfo->Version.contains("strongSwan", Qt::CaseInsensitive))
            IpsecType = TypeString = "L2TP (strongSwan)";
        else
            IpsecType = TypeString = "L2TP (FreeS/WAN)";
    } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::vtun)
        TypeString = "Vtun";


    if (!Name.isEmpty()) {

        int result = KMessageBox::questionYesNo(this, i18n("Really delete profile \"%1\" (type: %2, Server: %3)?"  , QString(GlobalConfig->currentProfile->getName()), TypeString, GlobalConfig->currentProfile->getGateway()), i18n("Delete?"));
        if (result == 3) {                // yes
            QuickConnectMenu->clear();
            mw->SessionCombo->clear();
            GlobalConfig->removeEntry(GlobalConfig->currentProfile->getName());

            if (GlobalConfig->AccountList->isEmpty()) {
                GlobalConfig->currentProfile = 0L;
                mw->SessionCombo->setEnabled(false);
                ConnectAction->setEnabled(false);
                mw->buttonConnect->setEnabled(false);
                DeleteSessionAction->setEnabled(false);
                GlobalConfig->lastProfile = "";
            } else {
                for (int accountIdx = 0; accountIdx < GlobalConfig->AccountList->size(); ++accountIdx) {
                    VpnAccountData *it = GlobalConfig->AccountList->at(accountIdx);
                    kDebug() << "item: " << it->getName() << endl;
                    QuickConnectMenu->addAction(it->getName());
                    mw->SessionCombo->insertItem(accountIdx, it->getName());
                }
                mw->SessionCombo->model()->sort(0);
                GlobalConfig->currentProfile = GlobalConfig->AccountList->first();
                GlobalConfig->lastProfile = GlobalConfig->AccountList->first()->getName();
                mw->SessionCombo->setEnabled(true);
                mw->buttonConnect->setEnabled(true);
                this->sessionToggled(GlobalConfig->currentProfile->getName());
            }

            slotStatusMsg(i18n("Profile \"%1\" deleted."  , QString(Name)), ID_FLASH_MSG);
            GlobalConfig->appendLogEntry(i18n("Profile \"%1\" deleted."  , QString(Name)) , KVpncEnum::info);
            GlobalConfig->saveOptions();
            saveGuiOptions();

        }
    }

}

void KVpnc::renameSessionClicked()
{

    VpnAccountData * it;
    bool nameOk = false;
    bool ok = true;
    QString newName = "";
    QString Oldname = GlobalConfig->currentProfile->getName();
    newName = KInputDialog::getText(i18n("New Name"), i18n("New name for profile:"), QString(GlobalConfig->currentProfile->getName()), &ok);
    while (nameOk == false) {
        for (int accountIdx = 0; accountIdx < GlobalConfig->AccountList->size(); ++accountIdx) {
            it = GlobalConfig->AccountList->at(accountIdx);
            if ((it != GlobalConfig->currentProfile) && (it->getName() == GlobalConfig->currentProfile->getName())) {
                //account->setName( QString( account->getName() + "_2" ) );
                //     KMessageBox::information ( this, i18n( "Profile name exists!\n It will be renamed to \"%1\"."  , QString( account->getName() )), i18n( "Name exist, renamed" ) );
                KMessageBox::error(this, i18n("Profile name exists."), i18n("Name Exists"));

                newName = KInputDialog::getText(i18n("New Name"), i18n("New name for profile:"), QString(GlobalConfig->currentProfile->getName() + "_2"), &ok);
                if (ok == false) {
                    KMessageBox::information(0, i18n("Rename was canceled."));
                    GlobalConfig->appendLogEntry(i18n("Rename was canceled."), KVpncEnum::info);
                    slotStatusMsg(i18n("Rename was canceled."), ID_FLASH_MSG);
                    return ;
                }
            }
            nameOk = true;
        }
        nameOk = true;
    }
    if (newName.isEmpty()) {
        nameOk = false;
    }

    if (nameOk) {
        for (int accountIdx = 0; accountIdx < GlobalConfig->AccountList->size(); ++accountIdx) {
            it = GlobalConfig->AccountList->at(accountIdx);
            if (it == GlobalConfig->currentProfile) {
                it = GlobalConfig->AccountList->first();
                GlobalConfig->currentProfile->setName(newName);
                nameOk = true;

                mw->SessionCombo->clear();
                QuickConnectMenu->clear();

                for (int AccountListIdx = 0; AccountListIdx < int(GlobalConfig->AccountList->count()); AccountListIdx++) {
                    QuickConnectMenu->addAction(GlobalConfig->AccountList->at(AccountListIdx) ->getName());
                    mw->SessionCombo->insertItem(AccountListIdx, GlobalConfig->AccountList->at(AccountListIdx) ->getName());
                }
                mw->SessionCombo->model()->sort(0);
                mw->SessionCombo->setCurrentItem(GlobalConfig->currentProfile->getName());
                GlobalConfig->removeEntry(Oldname);

                if (!mw->SessionCombo->isEnabled())
                    mw->SessionCombo->setEnabled(true);

                this->ConnectAction->setEnabled(true);
                sessionToggled(GlobalConfig->currentProfile->getName());

                KMessageBox::information(0, i18n("Rename of \"%1\" to \"%2\" was successful." , QString(Oldname), GlobalConfig->currentProfile->getName()));
                GlobalConfig->appendLogEntry(i18n("Rename of \"%1\" to \"%2\" was successful." , QString(Oldname), GlobalConfig->currentProfile->getName()), KVpncEnum::info);
                slotStatusMsg(i18n("Rename of \"%1\" to \"%2\" was successful."  , QString(Oldname), GlobalConfig->currentProfile->getName()), ID_FLASH_MSG);

                GlobalConfig->saveOptions();
                return;
            }
        }
    } else {
        GlobalConfig->appendLogEntry(i18n("Rename was canceled."), KVpncEnum::info);
        slotStatusMsg(i18n("Rename was canceled."), ID_FLASH_MSG);
    }
}

void KVpnc::sessionToggled(const QString& Name2)
{
    //  mw->DebugOutput->append( "sessionToggled" );
    if (Name2.isEmpty() || GlobalConfig->AccountList->isEmpty()) {
        this->DeleteSessionAction->setEnabled(false);
        //   this->advancedSessionAction->setEnabled(false);
        this->SaveSessionAction->setEnabled(false);
        return;
    } else {
        this->DeleteSessionAction->setEnabled(true);
        //   this->advancedSessionAction->setEnabled(true);
        this->SaveSessionAction->setEnabled(true);
        GlobalConfig->currentProfile = GlobalConfig->AccountList->first();
        QString Name = Name2;


        for (int SessionIdx = 0; SessionIdx < GlobalConfig->AccountList->count(); SessionIdx++) {
            if (!Name.isEmpty()) {
                if (QString(GlobalConfig->AccountList->at(SessionIdx)->getName()) == QString(Name)) {
                    // profile found
                    GlobalConfig->currentProfile = GlobalConfig->AccountList->at(SessionIdx);
                    mw->SessionCombo->setCurrentItem(GlobalConfig->AccountList->at(SessionIdx)->getName());


                    QString ProfileInfo = "";
                    QString TypeString = "";
                    QString Gateway = GlobalConfig->currentProfile->getGateway();
                    QString Username = GlobalConfig->currentProfile->getUserName();
                    //if ( GlobalConfig->KvpncDebugLevel > 2 )
                    //      GlobalConfig->appendLogEntry (i18n("Username: \"%1", Username), KVpncEnum::debug);
                    if (GlobalConfig->currentProfile->getDontSaveUsername() || (Username == ""))
                        Username = i18n("&lt;ask at connect&gt;");
                    QString IpsecId = "";
                    QString RemotePort=0;
                    QString IkeOptions = "";
                    QString EspOptions = "";
                    QString TunnelDeviceType=GlobalConfig->currentProfile->getTunnelDeviceType();

                    this->ExportOpenvpnProfileAction->setEnabled(false);

                    QString type = ""; // visible name
                    QString bin = "";  // executable name

                    ProfileInfo += "<table>";
                    if (GlobalConfig->KvpncDebugLevel > 2)
                        GlobalConfig->appendLogEntry(i18n("connectionType raw: %1" , QString().setNum(GlobalConfig->currentProfile->getConnectionType())), KVpncEnum::debug);

                    if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco) {
                        type = "vpnc";
                        bin = "vpnc";
                        TypeString =  i18n ( "Cisco (free)" );
                        ProfileInfo += "<tr><td>"+i18n("Type:")+"</td><td>"+TypeString+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Gateway (VPN server):")+"</td><td>"+Gateway+"</td></tr>";
                        IpsecId = GlobalConfig->currentProfile->getID();
                        ProfileInfo += "<tr><td>"+i18n("IPsec ID:")+"</td><td>"+IpsecId+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Username:")+"</td><td>"+Username+"</td></tr>";
                    } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig) {
                        type = "ciscovpnc";
                        bin = "vpnclient";
                        TypeString = i18n ( "Cisco (proprietary)" );
                        ProfileInfo += "<tr><td>"+i18n("Type:")+"</td><td>"+TypeString+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Gateway (VPN server):")+"</td><td>"+Gateway+"</td></tr>";
                        IpsecId = GlobalConfig->currentProfile->getID();
                        ProfileInfo += "<tr><td>"+i18n("IPsec ID:")+"</td><td>"+IpsecId+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Username:")+"</td><td>"+Username+"</td></tr>";
                    } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan) {
                        type = "ipsec";
                        bin = "ipsec";
                        TypeString =  i18n ( "IPsec (Openswan/strongSwan)" );
                        ProfileInfo += "<tr><td>"+i18n("Type:")+"</td><td>"+TypeString+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Gateway (VPN server):")+"</td><td>"+Gateway+"</td></tr>";
                        IpsecId = GlobalConfig->currentProfile->getSpecialLocalID();
                        ProfileInfo += "<tr><td>"+i18n("IPsec ID:")+"</td><td>"+IpsecId+"</td></tr>";
                        IkeOptions = GlobalConfig->currentProfile->getIpsecIke();
                        ProfileInfo += "<tr><td>"+i18n("IKE options:")+"</td><td>"+IkeOptions+"</td></tr>";
                        EspOptions = GlobalConfig->currentProfile->getIpsecEsp();
                        ProfileInfo += "<tr><td>"+i18n("ESP options:")+"</td><td>"+EspOptions+"</td></tr>";
                    } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon) {
                        type = "racoon";
                        bin = "racoon";
                        TypeString =  i18n ( "IPsec (ipsec-tools)" );
                        ProfileInfo += "<tr><td>"+i18n("Type:")+"</td><td>"+TypeString+"</td></tr>";
                        IpsecId = GlobalConfig->currentProfile->getSpecialLocalID();
                        ProfileInfo += "<tr><td>"+i18n("IPsec ID:")+"</td><td>"+IpsecId+"</td></tr>";
                        IkeOptions = GlobalConfig->currentProfile->getAuthenticationAlgorithm();
                        ProfileInfo += "<tr><td>"+i18n("Authentication algorithm:")+"</td><td>"+IkeOptions+"</td></tr>";
                        EspOptions = GlobalConfig->currentProfile->getEncryptionAlgorithm();
                        ProfileInfo += "<tr><td>"+i18n("Encryption algorithm:")+"</td><td>"+EspOptions+"</td></tr>";
                    } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp) {
                        type = "pptp";
                        bin = "pppd pptp";
                        TypeString =  i18n ( "PPTP" );
                        ProfileInfo += "<tr><td>"+i18n("Type:")+"</td><td>"+TypeString+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Gateway (VPN server):")+"</td><td>"+Gateway+"</td></tr>";
                        QString PptpOptions = "";
                        PptpOptions += "<tr><td colspan=\"2\"><table>";
                        if (GlobalConfig->currentProfile->getRequireMppe())
                            PptpOptions += "<tr><td>"+i18n("Require MPPE:")+"</td><td>"+ i18n("yes")+"</td></tr>";
                        else
                            PptpOptions += "<tr><td>"+i18n("Require MPPE:")+"</td><td>"+ i18n("no")+"</td></tr>";
                        if (GlobalConfig->currentProfile->getRefuse128BitEncryption())
                            PptpOptions += "<tr><td>"+i18n("Refuse 128 bit encryption:")+"</td><td>"+ i18n("yes")+"</td></tr>";
                        else
                            PptpOptions += "<tr><td>"+i18n("Refuse 128 bit encryption:")+"</td><td>"+ i18n("no")+"</td></tr>";
                        if (GlobalConfig->currentProfile->getRefuse40BitEncryption())
                            PptpOptions += "<tr><td>"+i18n("Refuse 40 bit encryption:")+"</td><td>"+ i18n("yes")+"</td></tr>";
                        else
                            PptpOptions += "<tr><td>"+i18n("Refuse 40 bit encryption:")+"</td><td>"+ i18n("no")+"</td></tr>";
                        if (GlobalConfig->currentProfile->getDisableMPPEComp())
                            PptpOptions += "<tr><td>"+i18n("Disable MPPE compression:")+"</td><td>"+ i18n("yes")+"</td></tr>";
                        else
                            PptpOptions += "<tr><td>"+i18n("Disable MPPE compression:")+"</td><td>"+ i18n("no")+"</td></tr>";
                        if (GlobalConfig->currentProfile->getUseNoBsdComp())
                            PptpOptions += "<tr><td>"+i18n("Disable BSD compression:")+"</td><td>"+ i18n("yes")+"</td></tr>";
                        else
                            PptpOptions += "<tr><td>"+i18n("Disable BSD compression:")+"</td><td>"+ i18n("no")+"</td></tr>";
                        if (GlobalConfig->currentProfile->getUseNoDeflate())
                            PptpOptions += "<tr><td>"+i18n("Disable deflate compression:")+"</td><td>"+ i18n("yes")+"</td></tr>";
                        else
                            PptpOptions += "<tr><td>"+i18n("Disable deflate compression:")+"</td><td>"+ i18n("no")+"</td></tr>";
                        if (GlobalConfig->currentProfile->getDisableHeaderCompression())
                            PptpOptions += "<tr><td>"+i18n("Disable header compression:")+"</td><td>"+ i18n("yes")+"</td></tr>";
                        else
                            PptpOptions += "<tr><td>"+i18n("Disable header compression:")+"</td><td>"+ i18n("no")+"</td></tr>";
                        if (GlobalConfig->currentProfile->getDisableAddressControlCompression())
                            PptpOptions += "<tr><td>"+i18n("Disable address control compression:")+"</td><td>"+ i18n("yes")+"</td></tr>";
                        else
                            PptpOptions += "<tr><td>"+i18n("Disable address control compression:")+"</td><td>"+ i18n("no")+"</td></tr>";
                        if (GlobalConfig->currentProfile->getDisableProtocolFieldCompression())
                            PptpOptions += "<tr><td>"+i18n("Disable protocol field compression:")+"</td><td>"+ i18n("yes")+"</td></tr>";
                        else
                            PptpOptions += "<tr><td>"+i18n("Disable protocol field compression:")+"</td><td>"+ i18n("no")+"</td></tr>";
                        if (GlobalConfig->currentProfile->getDisableMagicNumberNegotiation())
                            PptpOptions += "<tr><td>"+i18n("Disable magic number negotiation:")+"</td><td>"+ i18n("yes")+"</td></tr>";
                        else
                            PptpOptions += "<tr><td>"+i18n("Disable magic number negotiation")+"</td><td>"+ i18n("no")+"</td></tr>";
                        if (GlobalConfig->currentProfile->getDisableCcp())
                            PptpOptions += "<tr><td>"+i18n("Disable Compression Control Protocol negotiation:")+"</td><td>"+ i18n("yes")+"</td></tr>";
                        else
                            PptpOptions += "<tr><td>"+i18n("Disable Compression Control Protocol negotiation:")+"</td><td>"+ i18n("no")+"</td></tr>";
                        if (GlobalConfig->currentProfile->getDisableIpx())
                            PptpOptions += "<tr><td>"+i18n("Disable IPX protocol:")+"</td><td>"+ i18n("yes")+"</td></tr>";
                        else
                            PptpOptions += "<tr><td>"+i18n("Disable IPX protocol:")+"</td><td>"+ i18n("no")+"</td></tr>";
                        if (GlobalConfig->currentProfile->getAllowStatefulMode())
                            PptpOptions += "<tr><td>"+i18n("Allow stateful mode:")+"</td><td>"+ i18n("yes")+"</td></tr>";
                        else
                            PptpOptions += "<tr><td>"+i18n("Allow stateful mode:")+"</td><td>"+ i18n("no")+"</td></tr>";
                        QString NtDomainName = "-";
                        if ( GlobalConfig->currentProfile->getUseNtDomainName() )
                            NtDomainName = GlobalConfig->currentProfile->getNtDomainName();
                        PptpOptions += "<tr><td>"+i18n("NT domain name:")+"</td><td>"+ NtDomainName+"</td></tr>";
                        /*
                        ProfilePptpOptionsWidget->DnsServerCheckbox->setChecked( it->getUseDnsServer() );
                        ProfilePptpOptionsWidget->DnsServerLineedit->setText( it->getDnsServer() );
                        ProfilePptpOptionsWidget->UseNoIpDefaultCheckbox->setChecked( it->getUseNoIpDefault() );
                        ProfilePptpOptionsWidget->RequireEapCheckbox->setChecked(it->getRequireEap());

                        */
                        PptpOptions += "</table></td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Username:")+"</td><td>"+Username+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("PPTP options:")+"</td><td>"+PptpOptions+"</td></tr>";
                    } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn) {
                        type = "openvpn";
                        bin = "openvpn";
                        TypeString =  i18n ( "OpenVPN" );
                        ProfileInfo += "<tr><td>"+i18n("Type:")+"</td><td>"+TypeString+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Gateway (VPN server):")+"</td><td>"+Gateway+"</td></tr>";
                        int RemotePort = 1194;
                        if (GlobalConfig->currentProfile->getUseRemotePort())
                            RemotePort = GlobalConfig->currentProfile->getRemotePort();
                        ProfileInfo += "<tr><td>"+i18n("Remote port:")+"</td><td>"+QString().setNum(RemotePort)+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Username:")+"</td><td>"+Username+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Tunnel device type:")+"</td><td>"+TunnelDeviceType+"</td></tr>";

                        this->ExportOpenvpnProfileAction->setEnabled(true);
                    } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon) {
                        type = "l2tpd (racoon)";
                        if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd) {
                            bin = "racoon, l2tpd | xl2tpd";
                            TypeString =  i18n ( "L2TP (ipsec-tools + (x)l2tpd)" );
                        }
                        if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp) {
                            bin = "racoon, openl2tpd";
                            TypeString =  i18n ( "L2TP (ipsec-tools + openl2tpd)" );
                        }
                        ProfileInfo += "<tr><td>"+i18n("Type:")+"</td><td>"+TypeString+"</td></tr>";
                        IpsecId = GlobalConfig->currentProfile->getSpecialLocalID();
                        ProfileInfo += "<tr><td>"+i18n("IPsec ID:")+"</td><td>"+IpsecId+"</td></tr>";
                        IkeOptions = GlobalConfig->currentProfile->getAuthenticationAlgorithm();
                        ProfileInfo += "<tr><td>"+i18n("Authentication algorithm:")+"</td><td>"+IkeOptions+"</td></tr>";
                        EspOptions = GlobalConfig->currentProfile->getEncryptionAlgorithm();
                        ProfileInfo += "<tr><td>"+i18n("Encryption algorithm:")+"</td><td>"+EspOptions+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Gateway (VPN server):")+"</td><td>"+Gateway+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Username:")+"</td><td>"+Username+"</td></tr>";

                    } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
                        type = "l2tpd (ipsec)";
                        if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd ) {
                            bin = "ipsec, l2tpd | xl2tpd";
                            TypeString =  i18n ( "L2TP (Openswan/strongSwan + (x)l2tpd)" );
                        }
                        if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp ) {
                            bin = "ipsec, openl2tpd";
                            TypeString =  i18n ( "L2TP (Openswan/strongSwan + openl2tpd)" );
                        }
                        ProfileInfo += "<tr><td>"+i18n("Type:")+"</td><td>"+TypeString+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Gateway (VPN server):")+"</td><td>"+Gateway+"</td></tr>";
                        IkeOptions = GlobalConfig->currentProfile->getIpsecIke();
                        ProfileInfo += "<tr><td>"+i18n("IKE options:")+"</td><td>"+IkeOptions+"</td></tr>";
                        EspOptions = GlobalConfig->currentProfile->getIpsecEsp();
                        ProfileInfo += "<tr><td>"+i18n("ESP options:")+"</td><td>"+EspOptions+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Username:")+"</td><td>"+Username+"</td></tr>";
                    } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::vtun) {
                        type = "vtun";
                        bin = "vtund";
                        TypeString =  i18n ( "Vtun" );
                        ProfileInfo += "<tr><td>"+i18n("Gateway (VPN server):")+"</td><td>"+Gateway+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Username:")+"</td><td>"+Username+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Tunnel device type:")+"</td><td>"+TunnelDeviceType+"</td></tr>";
                    } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh) {
                        type = "ssh";
                        bin = "ssh, ksshaskpass | gnome-ssh-askpass";
                        TypeString =  i18n ( "SSH" );
                        ProfileInfo += "<tr><td>"+i18n("Type:")+"</td><td>"+TypeString+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Gateway (VPN server):")+"</td><td>"+Gateway+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Username:")+"</td><td>"+Username+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Tunnel device type:")+"</td><td>"+TunnelDeviceType+"</td></tr>";
                    } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_plain ) {
                        type = "l2tpd (plain)";
                        if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd ) {
                            bin = "l2tpd | xl2tpd";
                            TypeString =  i18n ( "L2TP ((x)l2tpd)" );
                        }
                        if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp ) {
                            bin = "openl2tpd";
                            TypeString =  i18n ( "L2TP (openl2tpd)" );
                        }
                        ProfileInfo += "<tr><td>"+i18n("Type:")+"</td><td>"+TypeString+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Gateway (VPN server):")+"</td><td>"+Gateway+"</td></tr>";
                        ProfileInfo += "<tr><td>"+i18n("Username:")+"</td><td>"+Username+"</td></tr>";
                    } else {
                        type = "other";
                        bin = "";
                    }

                    if (GlobalConfig->KvpncDebugLevel > 2)
                        GlobalConfig->appendLogEntry(i18n("Selected connection type: %1." , QString(type)), KVpncEnum::debug);

                    int Authtype = GlobalConfig->currentProfile->getAuthType();
                    QString AuthTypeText = "";
                    QString AuthTypePretty = "";
                    if (Authtype == VpnAccountData::cert) {
                        AuthTypeText = "cert";
                        AuthTypePretty = i18n("Certificate");
                    } else if (Authtype == VpnAccountData::psk) {
                        AuthTypeText = "psk";
                        AuthTypePretty = i18n("Pre shared key");
                    } else if (Authtype == VpnAccountData::hybrid) {
                        AuthTypeText = "hybrid";
                        AuthTypePretty = i18n("Hybrid");
                    } else {
                        AuthTypeText = "unknown auth";
                        AuthTypePretty = i18n("Unknown");
                    }
                    if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp ) {
                        AuthTypePretty = i18n("PPTP");
                        if ( GlobalConfig->currentProfile->getAuthMethod() == "chap")
                            AuthTypePretty += " ("+i18n("CHAP")+")";
                        if ( GlobalConfig->currentProfile->getAuthMethod() == "mschap")
                            AuthTypePretty += " ("+i18n("MSCHAP")+")";
                        if ( GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2")
                            AuthTypePretty += " ("+i18n("MSCHAP v2")+")";
                        if ( GlobalConfig->currentProfile->getAuthMethod() == "pap"  )
                            AuthTypePretty += " ("+i18n("PAP")+")";
                    }
                    if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon  || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan  ) {
                        if ( GlobalConfig->currentProfile->getAuthMethod() == "chap")
                            AuthTypePretty += " ("+i18n("L2TP:")+" "+i18n("CHAP")+")";
                        if ( GlobalConfig->currentProfile->getAuthMethod() == "mschap")
                            AuthTypePretty += " ("+i18n("L2TP:")+" "+i18n("MSCHAP")+")";
                        if ( GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2")
                            AuthTypePretty += " ("+i18n("L2TP:")+" "+i18n("MSCHAP v2")+")";
                        if ( GlobalConfig->currentProfile->getAuthMethod() == "pap"  )
                            AuthTypePretty += " ("+i18n("L2TP:")+" "+i18n("PAP")+")";

                    }
                    if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh ) {
                        AuthTypePretty = i18n("SSH");
                        if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())
                            AuthTypePretty += i18n(" (using password)");
                        else if (GlobalConfig->currentProfile->getPskIsInFile())
                            AuthTypePretty += i18n(" (using key: %1)", GlobalConfig->currentProfile->getPreSharedKeyFile());
                        else
                            AuthTypePretty += i18n(" (using key: %1)", GlobalConfig->currentProfile->getPreSharedKey());
                    }
                    if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_plain ) {
                        if ( GlobalConfig->currentProfile->getAuthMethod() == "chap")
                            AuthTypePretty = " "+i18n("CHAP");
                        if ( GlobalConfig->currentProfile->getAuthMethod() == "mschap")
                            AuthTypePretty = " "+i18n("MSCHAP");
                        if ( GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2")
                            AuthTypePretty = " "+i18n("MSCHAP v2");
                        if ( GlobalConfig->currentProfile->getAuthMethod() == "pap"  )
                            AuthTypePretty = " "+i18n("PAP");
                    }

                    if ( GlobalConfig->KvpncDebugLevel > 2 )
                        GlobalConfig->appendLogEntry(i18n("Selected auth type: %1." , QString(AuthTypePretty)), KVpncEnum::debug);
                    ProfileInfo += "<tr><td>"+i18n("Authentication:")+"</td><td>"+AuthTypePretty+"</td></tr>";



                    //ToolInfo *it;

                    QString TypeRequirementStatus="";
                    if (!GlobalConfig->ToolList->isEmpty()) {

                        bool UseSmartcardOk = true;
                        if (GlobalConfig->currentProfile->getUseSmartcard()) {
                            ToolInfo *Pkcs11ToolInfo = Utils(GlobalConfig).getToolInfo(QString("pkcs11-tool"));
                            if (Pkcs11ToolInfo->found)
                                UseSmartcardOk = true;
                            else
                                UseSmartcardOk = false;
                        }

                        if (type != "pptp" && type != "l2tpd (racoon)" && type != "l2tpd (ipsec)" && type != "ssh" && type != "l2tpd (plain)") {
                            if (Utils(GlobalConfig).getToolInfo(bin) != 0 && Utils(GlobalConfig).getToolInfo(bin)->found) {
                                if (!GlobalConfig->currentProfile->getUseSmartcard()) {
                                    // program is installed
                                    this->ConnectAction->setEnabled(true);
                                    mw->buttonConnect->setEnabled(true);

                                    if (GlobalConfig->KvpncDebugLevel > 2)
                                        GlobalConfig->appendLogEntry(i18n("The required daemon (%1) is available, connect will be enabled." , bin), KVpncEnum::info);
                                    TypeRequirementStatus = i18n ( "Daemon (%1) available",bin);
                                } else {
                                    if (UseSmartcardOk == false) {
                                        this->ConnectAction->setEnabled(false);
                                        mw->buttonConnect->setEnabled(false);
                                        GlobalConfig->appendLogEntry(i18n("The required helper program (%1) is not available, connect will be disabled." , QString("pkcs11-tool")), KVpncEnum::error);
                                        TypeRequirementStatus = i18n ( "Helper program (%1) not available", QString("pkcs11-tool") );

                                    } else {
                                        this->ConnectAction->setEnabled(true);
                                        mw->buttonConnect->setEnabled(true);
                                        if (GlobalConfig->KvpncDebugLevel > 2)
                                            GlobalConfig->appendLogEntry(i18n("The required daemon (%1) and helper program (%2) is available, connect will be enabled." , bin , QString("pkcs11-tool")), KVpncEnum::info);
                                        TypeRequirementStatus = i18n ( "Daemon (%1) and helper program (%2) available", bin, QString("pkcs11-tool") );
                                    }
                                }
                            } else {
                                this->ConnectAction->setEnabled(false);
                                mw->buttonConnect->setEnabled(false);
                                GlobalConfig->appendLogEntry(i18n("The required daemon (%1) is not available, connect will be disabled." , bin), KVpncEnum::error);
                                TypeRequirementStatus = i18n ( "Daemon (%1) not available", bin);
                            }
                        } else {
                            if (type == "l2tpd (racoon)") {
                                bool racoon_and_l2tpd_available = false;
                                bool racoon_and_xl2tpd_available = false;
                                bool racoon_and_openl2tp_available = false;
                                if (Utils(GlobalConfig).getToolInfo("racoon")->found) {
                                    if (Utils(GlobalConfig).getToolInfo("l2tpd")->found)
                                        racoon_and_l2tpd_available = true;
                                    if (Utils(GlobalConfig).getToolInfo("xl2tpd")->found)
                                        racoon_and_xl2tpd_available = true;
                                    if (Utils(GlobalConfig).getToolInfo("openl2tpd")->found)
                                        racoon_and_openl2tp_available = true;
                                }
                                if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd) {
                                    if (racoon_and_l2tpd_available) {
                                        // programs are installed
                                        if (GlobalConfig->KvpncDebugLevel > 2)
                                            GlobalConfig->appendLogEntry(i18n("The required daemons (%1 and %2) are available, connect will be enabled." , QString("racoon") , QString("l2tpd")), KVpncEnum::info);
                                        TypeRequirementStatus = i18n ( "Daemons (%1 and %2) available", QString("racoon"), QString("l2tpd") );

                                        this->ConnectAction->setEnabled(true);
                                        mw->buttonConnect->setEnabled(true);
                                    } else if (racoon_and_xl2tpd_available) {
                                        // programs are installed
                                        if (GlobalConfig->KvpncDebugLevel > 2)
                                            GlobalConfig->appendLogEntry(i18n("The required daemons (%1 and %2) are available, connect will be enabled." , QString("racoon") , QString("xl2tpd")), KVpncEnum::info);
                                        TypeRequirementStatus = i18n ( "Daemons (%1 and %2) available", QString("racoon"), QString("xl2tpd") );

                                        this->ConnectAction->setEnabled(true);
                                        mw->buttonConnect->setEnabled(true);
                                    } else if (racoon_and_l2tpd_available == false &&  racoon_and_xl2tpd_available == false) {
                                        GlobalConfig->appendLogEntry(i18n("The required daemons (%1 and %2) are not available, connect will be disabled."  , QString("racoon") , QString("l2tpd/xl2tpd")), KVpncEnum::error);
                                        TypeRequirementStatus = i18n ( "Daemons (%1 and %2) not available", QString("racoon"), QString("l2tpd/xl2tpd") );
                                    }
                                }
                                if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp) {
                                    if (racoon_and_openl2tp_available) {
                                        // programs are installed
                                        if (GlobalConfig->KvpncDebugLevel > 2)
                                            GlobalConfig->appendLogEntry(i18n("The required daemons (%1 and %2) are available, connect will be enabled."  , QString("racoon") , QString("openl2tp")), KVpncEnum::info);
                                        TypeRequirementStatus = i18n ( "Daemons (%1 and %2) available", QString("racoon"), QString("openl2tp") );

                                        this->ConnectAction->setEnabled(true);
                                        mw->buttonConnect->setEnabled(true);
                                    }
                                }
                            }
                            if (type == "l2tpd (ipsec)") {
                                bool ipsec_and_l2tpd_available = false;
                                bool ipsec_and_xl2tpd_available = false;
                                bool ipsec_and_openl2tp_available = false;
                                if (Utils(GlobalConfig).getToolInfo("ipsec")->found) {
                                    if (Utils(GlobalConfig).getToolInfo("l2tpd")->found)
                                        ipsec_and_l2tpd_available = true;
                                    if (Utils(GlobalConfig).getToolInfo("xl2tpd")->found)
                                        ipsec_and_xl2tpd_available = true;
                                    if (Utils(GlobalConfig).getToolInfo("openl2tpd")->found)
                                        ipsec_and_openl2tp_available = true;
                                }

                                QString daemon;
                                if (ipsec_and_l2tpd_available) {
                                    daemon = "l2tpd";
                                }
                                if (ipsec_and_xl2tpd_available) {
                                    daemon = "xl2tpd";
                                }
                                if (ipsec_and_openl2tp_available) {
                                    daemon = "openl2tp";
                                }
                                if (ipsec_and_l2tpd_available ||
                                        ipsec_and_xl2tpd_available ||
                                        ipsec_and_openl2tp_available) {
                                    if (!GlobalConfig->currentProfile->getUseSmartcard()) {

                                        if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd) {
                                            if (ipsec_and_l2tpd_available) {
                                                // programs are installed
                                                if (GlobalConfig->KvpncDebugLevel > 2)
                                                    GlobalConfig->appendLogEntry(i18n("The required daemons (%1 and %2) are available, connect will be enabled."  , QString("ipsec"), QString("l2tpd")), KVpncEnum::info);
                                                TypeRequirementStatus = i18n ( "Daemons (%1 and %2) available",QString("ipsec"),QString("l2tpd") );

                                                this->ConnectAction->setEnabled(true);
                                                mw->buttonConnect->setEnabled(true);
                                            } else if (ipsec_and_xl2tpd_available) {
                                                // programs are installed
                                                if (GlobalConfig->KvpncDebugLevel > 2)
                                                    GlobalConfig->appendLogEntry(i18n("The required daemons (%1 and %2) are available, connect will be enabled."  , QString("ipsec") , QString("xl2tpd")), KVpncEnum::info);
                                                TypeRequirementStatus = i18n ( "Daemons (%1 and %2) available", QString("ipsec"), QString("xl2tpd") );

                                                this->ConnectAction->setEnabled(true);
                                                mw->buttonConnect->setEnabled(true);
                                            } else if (ipsec_and_l2tpd_available == false &&  ipsec_and_xl2tpd_available == false) {
                                                GlobalConfig->appendLogEntry(i18n("The required daemons (%1 and %2) are not available, connect will be disabled." , QString("ipsec") , QString("l2tpd/xl2tpd")), KVpncEnum::error);
                                                TypeRequirementStatus = i18n ( "Daemons (%1 and %2) not available",QString("ipsec"), QString("xl2tpd") );
                                            }
                                        }
                                        if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp) {
                                            if (ipsec_and_openl2tp_available) {
                                                // programs are installed
                                                if (GlobalConfig->KvpncDebugLevel > 2) {
                                                    GlobalConfig->appendLogEntry(i18n("The required daemons (ipsec and %1) are available,"
                                                                                      " connect will be enabled.",
                                                                                      daemon),
                                                                                 KVpncEnum::info);
                                                }
                                                TypeRequirementStatus = i18n ( "Daemons (%1 and %2) available", QString("ipsec"),  daemon );

                                                this->ConnectAction->setEnabled(true);
                                                mw->buttonConnect->setEnabled(true);
                                            } else if (ipsec_and_openl2tp_available == false) {
                                                GlobalConfig->appendLogEntry(i18n("The required daemons (%1 and %2) are not available, connect will be disabled." , QString("ipsec") , QString("openl2tp")), KVpncEnum::error);
                                                TypeRequirementStatus = i18n ( "Daemons (%1 and %2) not available", QString("ipsec"), QString("openl2tp") );
                                            }
                                        }
                                    } else {
                                        if (GlobalConfig->currentProfile->getUseSmartcard()) {
                                            if (UseSmartcardOk == false) {
                                                this->ConnectAction->setEnabled(false);
                                                mw->buttonConnect->setEnabled(false);
                                                GlobalConfig->appendLogEntry(i18n("The required helper program (%1) is not available, connect will be disabled." , QString("pkcs11-tool")), KVpncEnum::error);
                                                TypeRequirementStatus = i18n ( "Helper program (%1) not available", QString("pkcs11-tool") );

                                            } else {
                                                this->ConnectAction->setEnabled(true);
                                                mw->buttonConnect->setEnabled(true);
                                                if (GlobalConfig->KvpncDebugLevel > 2) {
                                                    GlobalConfig->appendLogEntry(i18n("The required daemons (ipsec and %1)"
                                                                                      " and helper program (pkcs11-tool) are available,"
                                                                                      " connect will be enabled.",
                                                                                      daemon),
                                                                                 KVpncEnum::info);
                                                }
                                                TypeRequirementStatus = i18n ( "Daemons (%1 and %2) available", QString("ipsec"), daemon);
                                            }
                                        }
                                    }
                                } else {
                                    GlobalConfig->appendLogEntry(i18n("The required daemons (%1 and %2) are not available, connect will be disabled." , QString("ipsec") , QString("l2tpd/xl2tpd")), KVpncEnum::error);
                                }
                            }
                            if (type == "pptp") {
                                bool pppd_and_pptp_available = false;
                                if (Utils(GlobalConfig).getToolInfo("pppd")->found) {
                                    if (Utils(GlobalConfig).getToolInfo("pptp")->found)
                                        pppd_and_pptp_available = true;
                                }
                                if (pppd_and_pptp_available) {
                                    // programs are installed
                                    if (GlobalConfig->KvpncDebugLevel > 2)
                                        GlobalConfig->appendLogEntry(i18n("The required daemons (%1 and %2) are available, connect will be enabled."  , QString("pppd") , QString("pptp")), KVpncEnum::info);
                                    TypeRequirementStatus = i18n ( "Daemons (%1 and %2) available", QString("pppd"), QString("pptp") );

                                    this->ConnectAction->setEnabled(true);
                                    mw->buttonConnect->setEnabled(true);

                                } else {
                                    GlobalConfig->appendLogEntry(i18n("The required daemons (%1 and %2) are not available, connect will be disabled."  , QString("pppd"), QString("pptp")), KVpncEnum::error);
                                    TypeRequirementStatus = i18n ( "Daemons (%1 and %2) not available", QString("pppd"), QString("pptp") );
                                }
                            }
                            if (type == "ssh") {
                                bool ssh_and_kaskpass_available = false;
                                bool ssh_and_gnomeaskpass_available = false;
                                if (Utils(GlobalConfig).getToolInfo("ssh")->found) {
                                    if (Utils(GlobalConfig).getToolInfo("ksshaskpass")->found)
                                        ssh_and_kaskpass_available = true;
                                    if (Utils(GlobalConfig).getToolInfo("gnome-ssh-askpass")->found)
                                        ssh_and_gnomeaskpass_available = true;
                                }
                                if (ssh_and_kaskpass_available) {
                                    // programs are installed
                                    if (GlobalConfig->KvpncDebugLevel > 2)
                                        GlobalConfig->appendLogEntry(i18n("The required programs (%1 and %2) are available, connect will be enabled." , QString("ssh") , QString("ksshaskpass")), KVpncEnum::info);
                                    TypeRequirementStatus = i18n ( "Daemons (%1 and %2) available", QString("ssh"), QString("ksshaskpass") );

                                    this->ConnectAction->setEnabled(true);
                                    mw->buttonConnect->setEnabled(true);

                                } else if (ssh_and_gnomeaskpass_available) {
                                    // programs are installed
                                    if (GlobalConfig->KvpncDebugLevel > 2)
                                        GlobalConfig->appendLogEntry(i18n("The required programs (%1 and %2) are available, connect will be enabled." , QString("ssh") , QString("gnome-ssh-askpass")), KVpncEnum::info);
                                    TypeRequirementStatus = i18n ( "Daemons (%1 and %2) available", QString("ssh"), QString("gnome-ssh-askpass") );

                                    this->ConnectAction->setEnabled(true);
                                    mw->buttonConnect->setEnabled(true);

                                } else {
                                    GlobalConfig->appendLogEntry(i18n("The required programs (%1 and %2) are not available, connect will be disabled." , QString("pppd"), i18n("%1 or %2" , QString("ksshaskpass") , QString("gnome-ssh-askpass"))), KVpncEnum::error);
                                    TypeRequirementStatus = i18n ( "Daemons (%1 and %2) not available", QString("pppd"), i18n ( "%1 or %2", QString("ksshaskpass"), QString("gnome-ssh-askpass") ) );
                                }
                            }
                            if ( type == "l2tpd (plain)" ) {
                                bool l2tpd_available = false;
                                bool xl2tpd_available = false;
                                bool openl2tp_available=false;

                                if ( Utils ( GlobalConfig ).getToolInfo ( "l2tpd" )->found )
                                    l2tpd_available = true;
                                if ( Utils ( GlobalConfig ).getToolInfo ( "xl2tpd" )->found )
                                    xl2tpd_available = true;
                                if ( Utils ( GlobalConfig ).getToolInfo ( "openl2tpd" )->found )
                                    openl2tp_available = true;
                                if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd ) {
                                    if ( l2tpd_available ) {
                                        // programs are installed
                                        if ( GlobalConfig->KvpncDebugLevel > 2 )
                                            GlobalConfig->appendLogEntry ( i18n ( "The required daemon (%1) is available, connect will be enabled.",  QString("l2tpd") ), KVpncEnum::info );
                                        TypeRequirementStatus = i18n ( "Daemon (%1) available", QString("l2tpd") );

                                        this->ConnectAction->setEnabled ( TRUE );
                                        mw->buttonConnect->setEnabled ( TRUE );
                                    } else if ( xl2tpd_available ) {
                                        // programs are installed
                                        if ( GlobalConfig->KvpncDebugLevel > 2 )
                                            GlobalConfig->appendLogEntry ( i18n ( "The required daemon (%1) is available, connect will be enabled.", QString("xl2tpd") ), KVpncEnum::info );

                                        TypeRequirementStatus = i18n ( "Daemon (%1) available", QString("xl2tpd") );

                                        this->ConnectAction->setEnabled ( TRUE );
                                        mw->buttonConnect->setEnabled ( TRUE );
                                    } else if ( l2tpd_available==false &&  xl2tpd_available==false ) {
                                        GlobalConfig->appendLogEntry ( i18n ( "The required daemon (%1) is not available, connect will be disabled.", QString("l2tpd/xl2tpd") ), KVpncEnum::error );
                                        TypeRequirementStatus = i18n ( " (%1) not available", QString("xl2tpd") );
                                    }
                                }
                                if ( GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp ) {
                                    if ( openl2tp_available ) {
                                        // programs are installed
                                        if ( GlobalConfig->KvpncDebugLevel > 2 )
                                            GlobalConfig->appendLogEntry ( i18n ( "The required daemon (%1) is available, connect will be enabled.", QString("openl2tp") ), KVpncEnum::info );

                                        TypeRequirementStatus = i18n ( "Daemon (%1) available", QString("openl2tp") );

                                        this->ConnectAction->setEnabled ( TRUE );
                                        mw->buttonConnect->setEnabled ( TRUE );
                                    }
                                }
                            }


                        }
                    }
                    ProfileInfo += "<tr><td>"+i18n("Required tools:")+"</td><td>"+TypeRequirementStatus+"</td></tr>";
                    ProfileInfo += "</table>";
                    QToolTip::add( mw->SessionCombo, ProfileInfo );
                    break;
                }
            }
        }
    }
}

void KVpnc::slotDurationEvent()
{
    sec += 1;
    if (sec > 59) {
        sec = 0;
        min += 1;

    }
    if (min > 59) {
        sec = 0;
        min = 0;
        hour += 1;
    }

    if (!isHidden()) {
        QString StatusMsg = "";
        QString durationString(i18n("%1:%2:%3" , QString().sprintf("%02u", hour), QString().sprintf("%02u", min), QString().sprintf("%02u", sec)));
        QString Username = "";

        if (!GlobalConfig->TmpUsername.isEmpty())
            Username = GlobalConfig->TmpUsername;
        else
            Username = GlobalConfig->currentProfile->getUserName();

        if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco) {
            StatusMsg = i18n("Connected: %2@%1, [%3], %4" , Username , GlobalConfig->currentProfile->getGateway() , PrettyTypeString , durationString);
        } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig) {
            StatusMsg = i18n("Connected: %2@%1, [%3], %4" , Username , GlobalConfig->currentProfile->getGateway() , PrettyTypeString , durationString);
        } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp) {
            StatusMsg = i18n("Connected: %2@%1 [%3], %4" , GlobalConfig->currentProfile->getGateway() , Username , PrettyTypeString , durationString);
        } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan ||
                   (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword() == true) ||
                   GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon ||
                   GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon ||
                   GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan
                  ) {
            if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && !(GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())) {
                StatusMsg = i18n("Connected: %1 [%2], %3" , GlobalConfig->currentProfile->getGateway() , PrettyTypeString , durationString);
            } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon) {
                StatusMsg = i18n("Connected: %1 [%2], %3" , GlobalConfig->currentProfile->getGateway() , PrettyTypeString , durationString);
            } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon) {
                StatusMsg = i18n("Connected: %2@%1 [%3], %4" , GlobalConfig->currentProfile->getGateway() , Username , PrettyTypeString , durationString);
            } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan || (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())) {
                StatusMsg = i18n("Connected: %2@%1 [%3], %4" , GlobalConfig->currentProfile->getGateway() , Username , PrettyTypeString , durationString);
            } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn) {
                StatusMsg = i18n("Connected: %2@%1 [%3], %4" , GlobalConfig->currentProfile->getGateway() , Username , PrettyTypeString , durationString);
            }

        } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn) {
            StatusMsg = i18n("Connected: %1, [%2], %3" , GlobalConfig->currentProfile->getGateway() , PrettyTypeString , durationString);
        } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::vtun) {
            StatusMsg = i18n("Connected: %1, [%2], %3"  , QString(GlobalConfig->currentProfile->getGateway())  , QString(PrettyTypeString), durationString);
        } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh) {
            StatusMsg = i18n("Connected: %1@%2 [%3], %4"  , QString(Username), GlobalConfig->currentProfile->getGateway(), PrettyTypeString , durationString);
        }
        else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_plain)
        {
            StatusMsg = i18n("Connected: %2@%1 [%3], %4", GlobalConfig->currentProfile->getGateway(), Username, PrettyTypeString, durationString);
        }


        slotStatusMsg(StatusMsg, ID_CONNECTION_MSG);
    }
    /*
    runningCheckCounter += 1;
    if ( runningCheckCounter == runningCheckTimeout ) {
    if ( !ConnectProcess->isRunning() ) {
    KMessageBox::error( this, i18n( "Connection lost in last %1 seconds." , QString().setNum( runningCheckTimeout ) ) );
    GlobalConfig->appendLogEntry ( i18n( "Connection to %1 lost at %2" , mw->gatewayLineEdit->text() , QDateTime::currentDateTime().toString( Qt::TextDate ) ),KVpncEnum::info );
    terminateConnection ( ConnectProcess );
    } else {
    runningCheckCounter = 0;
    }
    }
    */
//  if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco )
//  {
//   int connecttime_seconds = sec + min * 60 + hour * 60 * 60;
//   int PeerTimeout = GlobalConfig->currentProfile->getPeerTimeout();
//   if ( PeerTimeout > 0 && connecttime_seconds > PeerTimeout )
//   {
//    GlobalConfig->appendLogEntry ( i18n ( "Peer timeout value (%1 s) reached. Reconnecing..." , PeerTimeout ), KVpncEnum::info );
//    disconnectClicked();
//    sleep ( 2 );
//    connectClicked();
//   }
//  }
}

void KVpnc::showDockTooltip(const QPoint &p)
{
    QString IP;
    if (GlobalConfig->showInterfaceIPinTooltip) {
        if (TunnelInterfaceIP.isEmpty()) {
            if (GlobalConfig->currentProfile && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn) {
                NetworkInterface iface(GlobalConfig, parent);
                TunnelInterfaceIP = iface.getInterfaceIP(OpenvpnDevice);
            }
            if (GlobalConfig->currentProfile && GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh) {
                NetworkInterface iface(GlobalConfig, parent);

                // FIXME make it dynamiclly
                if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tun")
                    TunnelInterfaceIP = iface.getInterfaceIP("tun0");
                else
                    TunnelInterfaceIP = iface.getInterfaceIP("tap0");
            }
            //   else if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon ) {
            //    NetworkInterface iface( GlobalConfig, parent );
            //
            //    //FIXME
            //    TunnelInterfaceIP = iface.getInterfaceIP( "ppp0" );
            //   }
        }

        IP = TunnelInterfaceIP;
        if (IP.isEmpty())
            IP = i18n("none");
    }
    QString durationString ="";
    QString ToolTipMsg = "<table>";

    QString Username = "";
    QString ConnectionStatus="";

    if (GlobalConfig->status == KVpncEnum::connected || GlobalConfig->status == KVpncEnum::connecting) {
        if (GlobalConfig->status == KVpncEnum::connected) {
            ConnectionStatus = i18n("connected");
            durationString = (i18n("%1:%2:%3" , QString().sprintf("%02u", hour), QString().sprintf("%02u", min), QString().sprintf("%02u", sec)));
        } else {
            ConnectionStatus = i18n("connecting");
        }

        if (!GlobalConfig->TmpUsername.isEmpty())
            Username = GlobalConfig->TmpUsername;
        else
            Username = GlobalConfig->currentProfile->getUserName();

        ToolTipMsg += "<tr><td>"+i18n("Status:")+"</td><td>"+ConnectionStatus+"</td></tr>";
        ToolTipMsg += "<tr><td>"+i18n("Server:")+"</td><td>"+QString(GlobalConfig->currentProfile->getGateway())+"</td></tr>";
        ToolTipMsg += "<tr><td>"+i18n("Type:")+"</td><td>"+QString(PrettyTypeString)+"</td></tr>";

        if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig)
            ToolTipMsg += "<tr><td>"+i18n("IPSec ID:")+"</td><td>"+GlobalConfig->currentProfile->getID()+"</td></tr>";


        if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp ||
                GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan ||
                (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())) {
            ToolTipMsg += "<tr><td>"+i18n("user:")+"</td><td>"+QString(Username)+"</td></tr>";
        }
        if ((GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig  || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp ||
                GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon ||
                GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan ||
                GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn ||
                GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh) && GlobalConfig->showInterfaceIPinTooltip == true)
            ToolTipMsg += "<tr><td>"+i18n("tunnel IP:")+"</td><td>"+QString(IP)+"</td></tr>";

        if ( GlobalConfig->currentProfile->getUseLeftSourceIp() &&  (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan)  && GlobalConfig->showInterfaceIPinTooltip == true)
        {
            ToolTipMsg += "<tr><td>"+i18n ("Virtual IP:")+"</td><td>"+GlobalConfig->currentProfile->getLeftSourceIp()+"</td></tr>";
        }


        if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn && GlobalConfig->currentProfile->getUseHttpProxy()) {
            ToolTipMsg += "<tr><td>"+i18n("HTTP proxy:")+"</td><td>"+GlobalConfig->currentProfile->getHttpProxy()+":"+QString().setNum(GlobalConfig->currentProfile->getHttpProxyPort())+"</td></tr>";
            if (GlobalConfig->currentProfile->getUseHttpProxyAuth()) {
                ToolTipMsg += "<tr><td>"+i18n("HTTP proxy type:")+"</td><td>"+GlobalConfig->currentProfile->getHttpProxyAuthType().toUpper()+"</td></tr>";
                ToolTipMsg += "<tr><td>"+i18n("HTTP proxy user:")+"</td><td>"+GlobalConfig->currentProfile->getHttpProxyUser()+"</td></tr>";
            }
        }

        if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco  || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn ||
                GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh) {
            ToolTipMsg += "<tr><td>"+i18n("Tunnel device type:")+"</td><td>"+QString(GlobalConfig->currentProfile->getTunnelDeviceType())+"</td></tr>";
        }

        if (GlobalConfig->showConnectionTimeInTooltip)
            ToolTipMsg += "<tr><td>"+i18n("Duration:")+"</td><td>"+durationString+"</td></tr>";
    }
    else if (GlobalConfig->status == KVpncEnum::disconnected) {
        ConnectionStatus = "<tr><td>"+i18n("Status:")+"</td><td>"+i18n("disconnected")+"</td></tr>";
        ToolTipMsg = ConnectionStatus;
    }
    ToolTipMsg += "</table>";
    KVpncDock->setToolTip(ToolTipMsg);
    KVpncDock->toolTip();
}

void KVpnc::setGuiStatus(int status)
{

    QString durationString = "";
    QString DaemonString = "";
    QString ToolTipMsg = "";
    QString ConnectMsg = "";
    QString LogMsg = "";
    QString ConnectionStatus = i18n("unknown");
    QString Username = "";
    if (status == KVpncEnum::connected) {
        setWindowIcon(KIcon("connected"));

        durationString = (i18n("%1:%2:%3" , QString().sprintf("%02u", hour) , QString().sprintf("%02u", min) , QString().sprintf("%02u", sec)));
        QString ConnectMsg = "";
        QString LogMsg = "";
        QString ToolTipMsg = "";
        QString DaemonString = "";
        ConnectionStatus = i18n("connected");

        if (!GlobalConfig->TmpUsername.isEmpty())
            Username = GlobalConfig->TmpUsername;
        else
            Username = GlobalConfig->currentProfile->getUserName();

        mw->SessionCombo->setEnabled(false);
        ImportCertAction->setEnabled(false);
        DeleteSessionAction->setEnabled(false);
        RenameSessionAction->setEnabled(false);
        ImportSessionAction->setEnabled(false);
        NewProfileWizardAction->setEnabled(false);

        KVpncDock->setStatus(KVpncEnum::connected);
        GlobalConfig->status = KVpncEnum::connected;
        statusColorLabel->setPixmap(connectedStatusPixmap);
        mw->buttonConnect->setEnabled(false);
        mw->buttonDisconnect->setEnabled(true);
        mw->SessionCombo->setEnabled(false);
        ConnectAction->setEnabled(false);
        DisconnectAction->setEnabled(true);
        PreferencesAction->setEnabled(false);
        ProfileManagerAction->setEnabled(false);
        NewProfileWizardAction->setEnabled(false);
        PrefAction ->setEnabled(false);

        ToolTipMsg = ConnectMsg;
        KVpncDock->setToolTip(ToolTipMsg);

        slotStatusMsg(i18n("Successful connected."), ID_FLASH_MSG);
        slotStatusMsg(ConnectMsg , ID_CONNECTION_MSG);
        GlobalConfig->appendLogEntry(ConnectMsg , KVpncEnum::success);

        //sleep(2);
        if (GlobalConfig->minimizeAfterConnect)
            hide();


        QuickConnectMenu = new QMenu(KVpncDock->menu());


        //setItemEnabled ( int id, bool enable )

    }
    else if (status == KVpncEnum::connecting) {
        setWindowIcon(KIcon("connecting"));
        mw->buttonConnect->setEnabled(false);
        mw->buttonDisconnect->setEnabled(true);
        mw->SessionCombo->setEnabled(false);
        ImportCertAction->setEnabled(false);
        ConnectAction->setEnabled(false);
        DisconnectAction->setEnabled(true);
        RenameSessionAction->setEnabled(false);
        DeleteSessionAction->setEnabled(false);
        ImportSessionAction->setEnabled(false);

        KVpncDock->setStatus(KVpncEnum::connecting);
        GlobalConfig->status = KVpncEnum::connecting;
        mw->SessionCombo->setEnabled(false);
        PreferencesAction->setEnabled(false);
        ProfileManagerAction->setEnabled(false);
        NewProfileWizardAction->setEnabled(false);
        PrefAction ->setEnabled(false);

        ConnectionStatus = i18n("connecting");

        statusColorLabel->setPixmap(connectingStatusPixmap);

        slotStatusMsg(i18n("Connecting..."), ID_CONNECTION_MSG);
        slotStatusMsg(i18n("Connecting..."), ID_FLASH_MSG);

        connectClicked();

    } else if (status == KVpncEnum::disconnected) {
        setWindowIcon(KIcon("disconnected"));
        mw->buttonConnect->setEnabled(true);
        mw->buttonDisconnect->setEnabled(false);
        DisconnectAction->setEnabled(false);
        ConnectAction->setEnabled(true);
        mw->SessionCombo->setEnabled(false);
        ImportCertAction->setEnabled(true);
        RenameSessionAction->setEnabled(true);
        DeleteSessionAction->setEnabled(true);
        ImportSessionAction->setEnabled(true);
        KVpncDock->setStatus(KVpncEnum::disconnected);
        mw->SessionCombo->setEnabled(true);
        PreferencesAction->setEnabled(true);
        ProfileManagerAction->setEnabled(true);
        NewProfileWizardAction->setEnabled(true);
        PrefAction ->setEnabled(true);


        KVpncDock->setToolTip(i18n("Disconnected"));

        statusColorLabel->setPixmap(disconnectedStatusPixmap);

        slotStatusMsg(i18n("Disconnected"), ID_CONNECTION_MSG);
        slotStatusMsg(i18n("Disconnected."), ID_FLASH_MSG);

        if (prevConnectionState == KVpncEnum::connected) {
            KNotification::event("connection finished",
                                 i18n("Connection \"%1\" finished",
                                      GlobalConfig->currentProfile->getName()));
        } else if (prevConnectionState == KVpncEnum::connecting) {
            KNotification::event("connect try canceled",
                                 i18n("Connect try to \"%1\" canceled",
                                      GlobalConfig->currentProfile->getName()));
        }
        GlobalConfig->status = KVpncEnum::disconnected;
    }
    if (status == KVpncEnum::connecting || status == KVpncEnum::connected) {
        if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig) {
            if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco) {
                PrettyTypeString = i18n("Cisco (free)");
                DaemonString = "vpnc";
            } else {
                PrettyTypeString =  i18n("Cisco (proprietary)");
                DaemonString = "vpnclient";
            }
            if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::psk) {
                ToolTipMsg = i18n("\nstatus: %6\nserver: %1\nuser: %2\nIPSec ID: %3\nduration: %4\nprofile: %5" , GlobalConfig->currentProfile->getGateway() , GlobalConfig->currentProfile->getUserName() , GlobalConfig->currentProfile->getID() , durationString , GlobalConfig->currentProfile->getName() + " [" + PrettyTypeString + "]", ConnectionStatus);

                ConnectMsg = i18n("%5: %2@%1, %3 [%4]" , GlobalConfig->currentProfile->getGateway() , Username , durationString , PrettyTypeString,  ConnectionStatus);

                LogMsg = i18n("Successful connected to server: \"%1\", user: \"%2\", IPSec ID: \"%3\" at %4" , GlobalConfig->currentProfile->getGateway() , GlobalConfig->currentProfile->getUserName() , GlobalConfig->currentProfile->getID() , QDateTime::currentDateTime().toString(Qt::TextDate)) + " [" + PrettyTypeString + "]";
            }
            if (GlobalConfig->currentProfile->getAuthType() == VpnAccountData::cert) {
                ToolTipMsg = i18n("\nstatus: %6\nserver: %1\nuser: %2\nIPSec ID: %3\nduration: %4\nprofile: %5" , GlobalConfig->currentProfile->getGateway() , Username , durationString , GlobalConfig->currentProfile->getName() + " [" + PrettyTypeString + "]", ConnectionStatus);

                ConnectMsg = i18n("%5: %2@%1, %3 [%4]" , GlobalConfig->currentProfile->getGateway() , Username , durationString , PrettyTypeString, ConnectionStatus);

                LogMsg = i18n("Successful connected to server: \"%1\", user: \"%2\" at %3" , GlobalConfig->currentProfile->getGateway() , Username , QDateTime::currentDateTime().toString(Qt::TextDate)) + " [" + PrettyTypeString + "]";
            }
        } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp) {
            PrettyTypeString =  i18n("PPTP");
            DaemonString = "pppd, pptp";
            ToolTipMsg = i18n("status: %5\nserver: %1\nuser: %2\nduration: %3\nprofile %4" , GlobalConfig->currentProfile->getGateway() , Username , durationString , GlobalConfig->currentProfile->getName() + " [" + PrettyTypeString + "]", ConnectionStatus);

            ConnectMsg = i18n("Connected: %2@%1, %3" , GlobalConfig->currentProfile->getGateway() , Username , durationString);

            QString TypeString2 = " [" + i18n("%1" , PrettyTypeString) + QString("]");
            LogMsg = i18n("Successful connected to server \"%1\"\nuser: \"%2\" at %3" , GlobalConfig->currentProfile->getGateway() , Username , QString(QDateTime::currentDateTime().toString(Qt::TextDate)) + TypeString2);
        } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan || GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
            if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon) {
                PrettyTypeString =  i18n("racoon");
                DaemonString = "racoon";
                ConnectMsg = i18n("Policy was successfully activated, daemon (%1) is running and tunnel is up.", DaemonString);
            } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan) {
                PrettyTypeString = IpsecType; // openswan, strongswan, ...
                DaemonString = "ipsec";
                ConnectMsg = i18n("Policy was successful activated and daemon (%1) is running." , DaemonString);
            } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon) {
                PrettyTypeString =  i18n("L2TP (racoon)");
                DaemonString = "racoon, " + GlobalConfig->currentProfile->getL2tpDaemon();

                ToolTipMsg = i18n("status: %5\nserver: %1\nuser: %2\nduration: %3\nprofile %4"  , QString(GlobalConfig->currentProfile->getGateway()), Username , durationString  , QString(GlobalConfig->currentProfile->getName()) + " [" + PrettyTypeString + "]", ConnectionStatus);

                ConnectMsg = i18n("%5: %2@%1, %3 [%4]" , GlobalConfig->currentProfile->getGateway() , Username , durationString , PrettyTypeString, ConnectionStatus);
            } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
                PrettyTypeString = IpsecType;
                if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
                    DaemonString = "ipsec, " + GlobalConfig->currentProfile->getL2tpDaemon();
                ToolTipMsg = i18n("status: %5\nserver: %1\nuser: %2\nduration: %3\nprofile %4"  , QString(GlobalConfig->currentProfile->getGateway()), Username , durationString , QString(GlobalConfig->currentProfile->getName()) + " [" + PrettyTypeString + "]", ConnectionStatus);

                ConnectMsg = i18n("%4: %2@%1, %3"  , QString(GlobalConfig->currentProfile->getGateway()),  Username , durationString, ConnectionStatus);
            } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan && GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()) {
                PrettyTypeString = IpsecType;
                DaemonString = "ipsec";
                ToolTipMsg = i18n("status: %5\nserver: %1\nuser: %2\nduration: %3\nprofile %4"  , QString(GlobalConfig->currentProfile->getGateway()), Username , durationString  , QString(GlobalConfig->currentProfile->getName()) + " [" + PrettyTypeString + "]", ConnectionStatus);

                ConnectMsg = i18n("Connected: %2@%1, %3" , GlobalConfig->currentProfile->getGateway() , Username , durationString);
            }

            LogMsg = i18n("Policy successful activated and daemon (%1) running for server \"%2\" (%3) at date %4, profile \"%5\".", DaemonString, GlobalConfig->currentProfile->getGateway(), GlobalConfig->TmpGatewayIP, QDateTime::currentDateTime().toString(Qt::TextDate), GlobalConfig->currentProfile->getName()) + " [" + PrettyTypeString + "]";

        } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn) {
            PrettyTypeString =  i18n("OpenVPN");
            DaemonString = "openvpn";
            ToolTipMsg = i18n("status: %3 \nserver: %1\nduration: %2" , GlobalConfig->currentProfile->getGateway() , durationString, ConnectionStatus);

            ConnectMsg = i18n("Connected: %1, %2, profile \"%3\"" , GlobalConfig->currentProfile->getGateway() , durationString , GlobalConfig->currentProfile->getName() + " [" + PrettyTypeString + "]");

            LogMsg = i18n("Successful connected to server \"%1\" at %2, profile \"%3\"." , GlobalConfig->currentProfile->getGateway() , QDateTime::currentDateTime().toString(Qt::TextDate) , GlobalConfig->currentProfile->getName()) + " [" + PrettyTypeString + "]";
        } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::vtun) {
            PrettyTypeString =  i18n("Vtun");
            DaemonString = "vtun";
            ToolTipMsg = i18n("status: %3\nserver: %1\nduration: %2"  , QString(GlobalConfig->currentProfile->getGateway()) , durationString, ConnectionStatus);

            ConnectMsg = i18n("Connected: %1, %2, profile \"%3\""  , QString(GlobalConfig->currentProfile->getGateway()), durationString  , QString(GlobalConfig->currentProfile->getName() + " [" + PrettyTypeString + "]"));

            LogMsg = i18n("Successful connected to server \"%1\" at %2, profile \"%3\"."  , QString(GlobalConfig->currentProfile->getGateway()), QDateTime::currentDateTime().toString(Qt::TextDate)  , QString(GlobalConfig->currentProfile->getName()) + " [" + PrettyTypeString + "]");
        } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh) {
            PrettyTypeString =  i18n("SSH");
            DaemonString = "ssh";
            ToolTipMsg = i18n("status: %3\nserver: %1\nduration: %2"  , QString(GlobalConfig->currentProfile->getGateway()) , durationString, ConnectionStatus);

            ConnectMsg = i18n("%4: %1, %2, profile \"%3\""  , QString(GlobalConfig->currentProfile->getGateway()), durationString  , QString(GlobalConfig->currentProfile->getName() + " [" + PrettyTypeString + "]"));

            LogMsg = i18n("Successful connected to server \"%1\" at %2, profile \"%3\"." , GlobalConfig->currentProfile->getGateway() , QDateTime::currentDateTime().toString(Qt::TextDate) , GlobalConfig->currentProfile->getName()) + " [" + PrettyTypeString + "]";
        } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_plain) {
            PrettyTypeString = IpsecType;
            if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists())
                DaemonString = GlobalConfig->currentProfile->getL2tpDaemon();
            ToolTipMsg = i18n("status: %5\nserver: %1\nuser: %2\nduration: %3\nprofile %4", QString(GlobalConfig->currentProfile->getGateway()), Username, durationString , QString(GlobalConfig->currentProfile->getName()) + " [" + PrettyTypeString + "]", ConnectionStatus);

            ConnectMsg = i18n("%4: %2@%1, %3", QString(GlobalConfig->currentProfile->getGateway()), Username, durationString, ConnectionStatus);
        }
        if (status == KVpncEnum::connected)
            KNotification::event("connection established", ConnectMsg);
    }

}

void KVpnc::importKvpncSettingsClicked()
{
    QString filename = KFileDialog::getOpenFileName(QString("."), QString("*.xml *.kvpnc"), 0, i18n("KVpnc settings import"));

    if (!filename.isEmpty()) {
        bool openProfileManager = false;
        QString RetName = "";
        bool ret = GlobalConfig->importKvpncConfig(filename, RetName, openProfileManager);
        if (ret == true) {
            mw->SessionCombo->clear();
            QuickConnectMenu->clear();

            for (int AccountListIdx = 0; AccountListIdx < int(GlobalConfig->AccountList->count()); AccountListIdx++) {
                QuickConnectMenu->addAction(GlobalConfig->AccountList->at(AccountListIdx)->getName());
                mw->SessionCombo->insertItem(AccountListIdx, GlobalConfig->AccountList->at(AccountListIdx) ->getName());
            }
            mw->SessionCombo->model()->sort(0);
            if (!mw->SessionCombo->isEnabled())
                mw->SessionCombo->setEnabled(true);

            this->ConnectAction->setEnabled(true);
            if (!RetName.isEmpty()) {
                mw->SessionCombo->setCurrentItem(RetName);
                sessionToggled(RetName);
            }

//    KMessageBox::information ( 0, i18n ( "Import of \"%1\" was successful."  , QString( filename ) ));
//    GlobalConfig->appendLogEntry ( i18n ( "Import of \"%1\" was successful."  , QString( filename )), KVpncEnum::info );
//    slotStatusMsg ( i18n ( "Import of \"%1\" was successful."  , QString( filename )), ID_FLASH_MSG );
            if (openProfileManager == true)
                showProfileManagerClicked();
        }

    }
}

void KVpnc::exportKvpncSettingsClicked()
{
    QString filename = KFileDialog::getSaveFileName(QString(""), QString("*.xml *.kvpnc"), 0, i18n("KVpnc settings export"));

    if (!filename.isEmpty()) {
        GlobalConfig->exportKvpncConfig(filename);
//   KMessageBox::information( 0, i18n( "Export was successful." ), i18n( "Export success" ) );
    }
}

void KVpnc::importProfileClicked(QString file)
{

    ImportProfileDialog dlg(GlobalConfig, this, i18n("Import profile"), file);
    dlg.exec();
    dlg.resize(800, dlg.height());

    bool importOK = dlg.importOk;
    bool ok = false;
    bool openProfileManager = dlg.OpenProfileManagerCheckBox->isChecked();
    if (importOK) {
        VpnAccountData * account = dlg.acc;

        VpnAccountData * it;
        bool nameOk = false;
        while (nameOk == false) {
            for (int accountIdx = 0; accountIdx < GlobalConfig->AccountList->size(); ++accountIdx) {
                it = GlobalConfig->AccountList->at(accountIdx);
                if ( it->getName() == account->getName() ) {
                    //account->setName( QString( account->getName() + "_2" ) );
                    // 				KMessageBox::information ( this, i18n( "Profile name exists!\n It will be renamed to \"%1\"." ).arg( account->getName() ), i18n( "Name exist, renamed" ) );
                    KMessageBox::error ( 0, i18n ( "Profile name exists!" ), i18n ( "Name Exists" ) );
                    nameOk = false;
                    QString newName = KInputDialog::getText ( i18n ( "New Name" ), i18n ( "New name for profile:" ), QString ( account->getName() + "_2" ), &ok );
                    if (newName.isEmpty()) {
                        KMessageBox::information ( 0, i18n ( "Import was canceled." ) );
                        GlobalConfig->appendLogEntry ( i18n ( "Import was canceled." ), KVpncEnum::info );
                        return;
                    }
                    if (newName != it->getName() ) {
                        account->setName ( newName );
                        nameOk = true;
                    }
                } else {
                    nameOk = true;
                }

            }
            nameOk = true;
        }

        if (nameOk == true) {
            GlobalConfig->AccountList->append(account);
            mw->SessionCombo->clear();
            QuickConnectMenu->clear();

            for (int AccountListIdx = 0; AccountListIdx < int(GlobalConfig->AccountList->count()); AccountListIdx++) {
                QuickConnectMenu->addAction(GlobalConfig->AccountList->at(AccountListIdx) ->getName());
                mw->SessionCombo->insertItem(AccountListIdx, GlobalConfig->AccountList->at(AccountListIdx) ->getName());
            }
            mw->SessionCombo->model()->sort(0);
            mw->SessionCombo->setCurrentItem(account->getName());

            if (!mw->SessionCombo->isEnabled())
                mw->SessionCombo->setEnabled(true);

            this->ConnectAction->setEnabled(true);
            sessionToggled(account->getName());

            KMessageBox::information(0, i18n("Import of \"%1\" was successful." , account->getName()));
            GlobalConfig->appendLogEntry(i18n("Import of \"%1\" (%2) was successful." , account->getName() , "PCF"), KVpncEnum::info);
            slotStatusMsg(i18n("Import of \"%1\" (%2) was successful." , account->getName() , "PCF"), ID_FLASH_MSG);

            GlobalConfig->saveOptions();

            QString bin = "vpnc";
            ToolInfo *tool;
            if (!GlobalConfig->ToolList->isEmpty()) {
                for (int toolIdx = 0; toolIdx < GlobalConfig->ToolList->size(); ++toolIdx) {
                    tool = GlobalConfig->ToolList->at(toolIdx);
                    if (bin == tool->Name) {
                        if (tool->PathToExec.section('/', -1) != bin) {
                            // program is NOT installed
                            KMessageBox::information(this, i18n("The required tool (%1) is not installed, please install it before you are connecting and restart kvpnc."  , QString(bin), i18n("Tool Missing")));
                        }
                        break;
                    }
                }
            }
            if (openProfileManager == true)
                showProfileManagerClicked();
        } else {
            KMessageBox::information(0, i18n("Import was canceled."));
            GlobalConfig->appendLogEntry(i18n("Import was canceled."), KVpncEnum::info);
            slotStatusMsg(i18n("Import was canceled."), ID_FLASH_MSG);
        }
    }
}

void KVpnc::importProfileClicked()
{
    importProfileClicked("");
}

void KVpnc::importOpenvpnProfileClicked()
{
    importOpenvpnProfileClicked("");
}

void KVpnc::importOpenvpnProfileClicked(QString file)
{

    ImportOpenvpnProfileDialog dlg(GlobalConfig, this, i18n("Import OpenVPN profile"), file);
    dlg.exec();
    dlg.resize(800, dlg.height());
    bool importOK = dlg.importOk;
    bool openProfileManager = dlg.main->OpenProfileManagerCheckBox->isChecked();
    if (importOK) {
        VpnAccountData * account = dlg.acc;

        VpnAccountData * it;
        bool nameOk = false;
        bool ok = true;
        while (nameOk == false) {
            for (int accountIdx = 0; accountIdx < GlobalConfig->AccountList->size(); ++accountIdx) {
                it = GlobalConfig->AccountList->at(accountIdx);
                if (it->getName() == account->getName()) {
                    //account->setName( QString( account->getName() + "_2" ) );
                    //     KMessageBox::information ( this, i18n( "Profile name exists!\n It will be renamed to \"%1\"."  , QString( account->getName() ), i18n( "Name exist, renamed" ) );
                    KMessageBox::error(this, i18n("Profile name exists."), i18n("Name Exists"));

                    QString newName = KInputDialog::getText(i18n("New Name"), i18n("New name for profile:"), QString(account->getName() + "_2"), &ok);
                    if (ok == false) {
                        KMessageBox::information(0, i18n("Import was canceled."));
                        GlobalConfig->appendLogEntry(i18n("Import was canceled."), KVpncEnum::info);
                        slotStatusMsg(i18n("Import was canceled."), ID_FLASH_MSG);
                        return ;
                    } else {
                        it = GlobalConfig->AccountList->first();
                        account->setName(newName);
                        nameOk = true;
                    }
                }
                nameOk = true;
            }
            nameOk = true;
        }

        GlobalConfig->AccountList->append(account);
        mw->SessionCombo->clear();
        QuickConnectMenu->clear();

        for (int AccountListIdx = 0; AccountListIdx < int(GlobalConfig->AccountList->count()); AccountListIdx++) {
            QuickConnectMenu->addAction(GlobalConfig->AccountList->at(AccountListIdx) ->getName());
            mw->SessionCombo->insertItem(AccountListIdx, GlobalConfig->AccountList->at(AccountListIdx) ->getName());
        }
        mw->SessionCombo->model()->sort(0);
        mw->SessionCombo->setCurrentItem(account->getName());

        if (!mw->SessionCombo->isEnabled())
            mw->SessionCombo->setEnabled(true);

        this->ConnectAction->setEnabled(true);
        sessionToggled(account->getName());

        KMessageBox::information(0, i18n("Import of \"%1\" was successful."  , QString(account->getName())));
        GlobalConfig->appendLogEntry(i18n("Import of \"%1\" (%2) was successful."  , QString(account->getName()) , QString("OpenVPN")), KVpncEnum::info);
        slotStatusMsg(i18n("Import of \"%1\" (%2) was successful."  , QString(account->getName())  , QString("OpenVPN")), ID_FLASH_MSG);

        GlobalConfig->saveOptions();

        QString bin = "openvpn";
        ToolInfo *tool;
        if (!GlobalConfig->ToolList->isEmpty()) {
            for (int toolIdx = 0; toolIdx < GlobalConfig->ToolList->size(); ++toolIdx) {
                tool = GlobalConfig->ToolList->at(toolIdx);
                if (bin == tool->Name) {
                    if (tool->PathToExec.section('/', -1) != bin) {
                        // program is NOT installed
                        KMessageBox::information(this, i18n("The required tool (%1) is not installed, please install it before you are connecting and restart kvpnc."  , QString(bin), i18n("Tool Missing")));
                    }
                    break;
                }
            }
        }

        if (openProfileManager)
            showProfileManagerClicked();
    }
}

void KVpnc::importIpsecProfileClicked()
{
    QString filename = KFileDialog::getOpenFileName(QString("."), QString("*.ipsec *.conf"), 0, i18n("IPSec settings import"));

    if (!filename.isEmpty()) {
        bool openProfileManager = false;
        QString RetName = "";
        bool ret = GlobalConfig->importIpsecConfig(filename, RetName, openProfileManager);
        if (ret == true) {
            mw->SessionCombo->clear();
            QuickConnectMenu->clear();

            for (int AccountListIdx = 0; AccountListIdx < int(GlobalConfig->AccountList->count()); AccountListIdx++) {
                QuickConnectMenu->addAction(GlobalConfig->AccountList->at(AccountListIdx) ->getName());
                mw->SessionCombo->insertItem(AccountListIdx, GlobalConfig->AccountList->at(AccountListIdx) ->getName());
            }
            mw->SessionCombo->model()->sort(0);
            if (!mw->SessionCombo->isEnabled())
                mw->SessionCombo->setEnabled(true);

            this->ConnectAction->setEnabled(true);

            mw->SessionCombo->setCurrentItem(RetName);
            sessionToggled(RetName);

//    KMessageBox::information ( 0, i18n ( "Import of \"%1\" was successful."  , QString( filename ) ));
//    GlobalConfig->appendLogEntry ( i18n ( "Import of \"%1\" was successful."  , QString( filename )), KVpncEnum::info );
//    slotStatusMsg ( i18n ( "Import of \"%1\" was successful."  , QString( filename )), ID_FLASH_MSG );

        }
        if (openProfileManager == true)
            showProfileManagerClicked();

    }

}

void KVpnc::importFritzboxProfileClicked ()
{
    QString filename = KFileDialog::getOpenFileName ( QString ( "." ), QString ( "vpnuser_*.cfg" ), 0,i18n ( "Fritzbox VPN settings import" ) );

    if ( !filename.isEmpty() )
    {
        bool openProfileManager=false;
        QString RetName="";
        bool ret = GlobalConfig->importFritzboxConfig ( filename, RetName,openProfileManager );
        if ( ret == true ) {
            mw->SessionCombo->clear();
            QuickConnectMenu->clear();

            for (int AccountListIdx = 0; AccountListIdx < int(GlobalConfig->AccountList->count()); AccountListIdx++) {
                QuickConnectMenu->addAction(GlobalConfig->AccountList->at(AccountListIdx) ->getName());
                mw->SessionCombo->insertItem(AccountListIdx, GlobalConfig->AccountList->at(AccountListIdx) ->getName());
            }
            mw->SessionCombo->model()->sort(0);
            if ( !mw->SessionCombo->isEnabled() )
                mw->SessionCombo->setEnabled ( TRUE );

            this->ConnectAction->setEnabled ( true );

            mw->SessionCombo->setCurrentText ( RetName );
            sessionToggled ( RetName );

            // 			KMessageBox::information ( 0, i18n ( "Import of \"%1\" was successful." ).arg ( filename ) );
            // 			GlobalConfig->appendLogEntry ( i18n ( "Import of \"%1\" was successful." ).arg ( filename ), KVpncEnum::info );
            // 			slotStatusMsg ( i18n ( "Import of \"%1\" was successful." ).arg ( filename ), ID_FLASH_MSG );

        }
        if ( openProfileManager==true )
            showProfileManagerClicked();

    }

}

void KVpnc::slotCancelClicked()
{
    cancelClicked = true;
}

void KVpnc::addRouteRacoon()
{

    //  if ( RacoonHelperProcess->normalExit () )
    {
        //   disconnect( ConnectProcess, SIGNAL( processExited () ), this, SLOT( addRouteRacoon() ) );
        //   disconnect( ConnectProcess, SIGNAL( readyReadStandardOutput() ), this, SLOT( readFromStdout_racoon_helper() ) );
        //   disconnect( ConnectProcess, SIGNAL( readyReadStandardError() ), this, SLOT( readFromStderr_racoon_helper() ) );


        tmpPath = KStandardDirs::locateLocal("data", "kvpnc/");
        QString RacoonRouteSetScript = tmpPath + "/set_route." + GlobalConfig->currentProfile->getName() + ".sh";
        NetworkInterface iface(GlobalConfig, parent);
        QString defaultinterface = iface.getDefaultInterface();
        QString dev = "lo";

        QString RemoteNetAddr = GlobalConfig->currentProfile->getRemoteNetAddr();
        QString RemoteNetMask = GlobalConfig->currentProfile->getRemoteNetMask();
        QString RemoteNet = RemoteNetAddr + "/" + RemoteNetMask;

        tmpInterface = iface.getDefaultInterface();

        if (GlobalConfig->currentProfile->getUseVirtualIP())
            dev = QString(dev + ":100");
        else
            dev = tmpInterface;

        QFile RacoonSetRouteScript(RacoonRouteSetScript);
        QTextStream stream(&RacoonSetRouteScript);
        if (RacoonSetRouteScript.open(QIODevice::WriteOnly)) {
            if (GlobalConfig->currentProfile->getReplaceDefaultRoute()) {
                stream << GlobalConfig->pathToIp << " route show  | grep 'default via' > " + tmpPath + "/defaultroute_before." + GlobalConfig->currentProfile->getName() << "\n";
                stream << GlobalConfig->pathToRoute << " del default" << "\n";

                stream << GlobalConfig->pathToRoute << " add default gw " << GlobalConfig->currentProfile->getGateway() << " " << iface.getDefaultInterface() << "\n";
            }

            // FIXME racoon_l2tpd too?
            if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon && GlobalConfig->currentProfile->getUseRemoteNetwork() ) {
                if (GlobalConfig->currentProfile->getUseLeftSourceIp())
                {
                    // virtual ip
                }
                else
                {
                    stream << GlobalConfig->pathToRoute << " add -net " << RemoteNet << " " << dev << "\n";
                }
            }

            RacoonSetRouteScript.close();

            RouteProcess = new QProcess(this);
            QString proc = GlobalConfig->InterpreterShell;
            QStringList args;
            args.append(RacoonRouteSetScript);

            connect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_route()));
            connect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_route()));

            RouteProcess->setEnvironment(*env);
            RouteProcess->start(proc, args);
            if (!RouteProcess->waitForStarted()) {
                KMessageBox::error(this, i18n("Failed to start \"%1\"."  , QString("route (racoon)")));
                GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString("route (racoon)")) , KVpncEnum::error);
                disconnect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_route()));
                disconnect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_route()));
                delete RouteProcess;
                RouteProcess = 0L;
                disconnectClicked();
            } else {
                if (GlobalConfig->KvpncDebugLevel > 0) {
                    if (GlobalConfig->currentProfile->getReplaceDefaultRoute())
                        GlobalConfig->appendLogEntry(i18n("route (%1): route add default gw %2" , QString("racoon"), GlobalConfig->currentProfile->getGateway() + " " + tmpInterface), KVpncEnum::debug);

                    // FIXME racoon_l2tpd too?
                    if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon  && GlobalConfig->currentProfile->getUseRemoteNetwork() )
                        GlobalConfig->appendLogEntry(i18n("route (%1): route add -net %2"  , QString("racoon"), RemoteNet + " " + tmpInterface), KVpncEnum::debug);


                    waitForFinished(RouteProcess, 100);
//                     int waitCounter = 0;
//                     while (RouteProcess->state() == QProcess::Running && waitCounter < 500) {
//                         usleep(100);
//                         waitCounter += 100;
//                     }
//                     if (waitCounter > 500 && RouteProcess->state() == QProcess::Running)
//                         RouteProcess->kill();

                    disconnect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_route()));
                    disconnect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_route()));
                    delete RouteProcess;
                    RouteProcess = 0L;
                }
            }
        }
    }
}

void KVpnc::delRouteRacoon()
{

    //  if ( DisconnectProcess != 0 )
    {
        disconnect(DisconnectProcess, SIGNAL(processExited()), this, SLOT(delRouteRacoon()));

        tmpPath = KStandardDirs::locateLocal("data", "kvpnc/");
        QString RacoonRouteSetScript = tmpPath + "/remove_route." + GlobalConfig->currentProfile->getName() + ".sh";
        NetworkInterface iface(GlobalConfig, parent);
        QString dev = "lo";

        QString RemoteNetAddr = GlobalConfig->currentProfile->getRemoteNetAddr();
        QString RemoteNetMask = GlobalConfig->currentProfile->getRemoteNetMask();
        QString RemoteNet = RemoteNetAddr + "/" + RemoteNetMask;

        tmpInterface = iface.getDefaultInterface();

        if (GlobalConfig->currentProfile->getUseVirtualIP())
            dev = QString(dev + ":100");
        else
            dev = tmpInterface;

        QFile RacoonSetRouteScript(RacoonRouteSetScript);
        QTextStream stream(&RacoonSetRouteScript);
        if (RacoonSetRouteScript.open(QIODevice::WriteOnly)) {
            if (GlobalConfig->currentProfile->getReplaceDefaultRoute()) {
                stream << GlobalConfig->pathToRoute << " del default" << "\n";
                stream << GlobalConfig->pathToIp << " route add `cat " + tmpPath + "/defaultroute_before." + GlobalConfig->currentProfile->getName() << "`" << "\n";
            }

            // FIXME racoon_l2tpd too?
            if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon && GlobalConfig->currentProfile->getUseRemoteNetwork() ) {
                if (GlobalConfig->currentProfile->getUseLeftSourceIp())
                {
                    // virtual ip
                }
                else
                {
                    stream << GlobalConfig->pathToRoute << " del -net " << RemoteNet << " " << dev << "\n";
                }
            }

            RacoonSetRouteScript.close();

            RouteProcess = new QProcess(this);
            QString proc = GlobalConfig->InterpreterShell;
            QStringList args;
            args.append(RacoonRouteSetScript);

            connect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_route()));
            connect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_route()));
            //    connect( RouteProcess, SIGNAL( processExited () ), this, SLOT( removeIptablesRacoon() ) );

            RouteProcess->setEnvironment(*env);
            RouteProcess->start(proc, args);
            if (!RouteProcess->waitForStarted()) {
                KMessageBox::error(this, i18n("Failed to start \"%1\"."  , QString("del route (racoon)")));
                GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString("del route (racoon)")) , KVpncEnum::error);
                disconnect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_route()));
                disconnect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_route()));
                //    connect( DisconnectProcess, SIGNAL( processExited () ), this, SLOT( removeIptablesRacoon() ) );
                delete RouteProcess;
                RouteProcess = 0L;
                return;
            } else {
                if (GlobalConfig->KvpncDebugLevel > 0) {
                    if (GlobalConfig->currentProfile->getReplaceDefaultRoute())
                        GlobalConfig->appendLogEntry(i18n("route (%1): route del default gw %2"  , QString("racoon"), QString(GlobalConfig->currentProfile->getGateway() + " " + tmpInterface)), KVpncEnum::debug);

                    // FIXME racoon_l2tpd too?
                    if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon && GlobalConfig->currentProfile->getUseRemoteNetwork() )
                        GlobalConfig->appendLogEntry(i18n("route (%1): route del -net %2"  , QString("racoon"), QString(RemoteNet + " " + tmpInterface)), KVpncEnum::debug);
                }
                waitForFinished(RouteProcess, 100);
//                 int waitCounter = 0;
//                 while (RouteProcess->state() == QProcess::Running && waitCounter < 500) {
//                     usleep(100);
//                     waitCounter += 100;
//                 }
//                 if (waitCounter > 500 && RouteProcess->state() == QProcess::Running)
//                     RouteProcess->kill();
                disconnect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_route()));
                disconnect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_route()));
                //    connect( DisconnectProcess, SIGNAL( processExited () ), this, SLOT( removeIptablesRacoon() ) );
                delete RouteProcess;
                RouteProcess = 0L;
            }

        }
    }
}

void KVpnc::doIptablesRacoon()
{
    //  if ( ConnectProcess->normalExit () )
    {
        //   if ( ConnectProcess )
        //    disconnect( ConnectProcess, SIGNAL( processExited () ), this, SLOT( doIptablesRacoon() ) );
        /*
        iptables -I INPUT -p 50 -i $IFACE -s $VPNGW_IP -j ACCEPT
        */
        putenv((char*)("LC_ALL=C"));
        QProcess IptablesProcess(this);
        QString proc = GlobalConfig->InterpreterShell;
        QStringList args;
        args.append(tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".add_racoon.sh");

        //   connect( IptablesProcess, SIGNAL( processExited () ), this, SLOT( doRacoon() ) );
        IptablesProcess.setEnvironment(*env);
        IptablesProcess.start(proc, args);
        if (!IptablesProcess.waitForStarted()) {
            KMessageBox::error(this, i18n("Failed to start \"%1\"."  , QString("iptables." + GlobalConfig->currentProfile->getName() + ".add_racoon.sh")));
            GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString("iptables." + GlobalConfig->currentProfile->getName() + ".add_racoon.sh")) , KVpncEnum::error);
            disconnectClicked();
        } else {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("\"%1\" started."  , QString("iptables." + GlobalConfig->currentProfile->getName() + ".add_racoon.sh")) , KVpncEnum::debug);
            waitForFinished(&IptablesProcess, 100);
        }

    }
}

void KVpnc::doPingKickupTunnel()
{

    if ( GlobalConfig->KvpncDebugLevel > 4 )
        GlobalConfig->appendLogEntry ( i18n ( "Sending ping for kicking up the tunnel..." ), KVpncEnum::debug );
    /* first: kick up the tunnel */
    putenv ( ( char* ) ( "LC_ALL=C" ) );
    QProcess PingProcess;
    QString PathToPing = "/bin/ping";
    ToolInfo *Tool=0L;
    for (int toolIdx = 0; toolIdx < GlobalConfig->ToolList->size(); ++toolIdx) {
        Tool = GlobalConfig->ToolList->at(toolIdx);
        if ( Tool->Name == "ping" ) {
            PathToPing = Tool->PathToExec;
            break;
        }
    }
    QStringList args;
    args.append( "-c");
    args.append( "1" );
    args.append( "-w" );
    args.append( "2" );
    QString PingIp ="127.0.0.1";
    if (GlobalConfig->currentProfile->getUseRemoteNetwork())
        PingIp = GlobalConfig->currentProfile->getRemoteNetAddr();
    else
        PingIp = GlobalConfig->currentProfile->getGateway();
    args.append(PingIp);
    if ( GlobalConfig->KvpncDebugLevel > 4 )
        GlobalConfig->appendLogEntry ( i18n ( "Using IP address for ping: %1", PingIp ), KVpncEnum::debug );
    PingProcess.setEnvironment(*env);
    PingProcess.start(PathToPing, args);
    if (!PingProcess.waitForStarted()) {
        KMessageBox::error ( this, i18n ( "\"%1\" start failed!", QString("ping " + PingIp)) );
        GlobalConfig->appendLogEntry ( i18n ( "\"%1\" start failed!", QString("ping " + PingIp) ), KVpncEnum::error );
    } else {
        PingProcess.waitForFinished();
        if ( GlobalConfig->KvpncDebugLevel > 4 )
            GlobalConfig->appendLogEntry ( i18n ( "Kickup ping finished."), KVpncEnum::debug );
    }
}

void KVpnc::doRacoon(int, QProcess::ExitStatus)
{
    disconnect(RacoonHelperProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_racoon_helper()));
    disconnect(RacoonHelperProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_racoon_helper()));
    disconnect(RacoonHelperProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(doRacoon(int, QProcess::ExitStatus)));



    if (RacoonHelperProcess->exitStatus()  == QProcess::NormalExit) {
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("[racoon]: " + i18n("%1 finished." , QString("setkey")), KVpncEnum::debug);



        /*
        /usr/sbin/racoon -f <configfile> -l <logfile>
        */
        QFile f(tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log");
        if (f.exists())
            f.remove();
        QTextStream s(&f);
        if (f.open(QIODevice::WriteOnly)) {
            s << "\n";
        }
        f.close();
        s.setDevice(0);
        putenv((char*)("LC_ALL=C"));
        RacoonProcess = 0;
        RacoonProcess = new QProcess(this);
        QString proc = GlobalConfig->pathToRacoon;
        QStringList args;
        args.append("-F");    // foreground we want :)
        //args.append ( "-v" );
        //args.append ( "-dd" );
        args.append("-f");
        args.append(tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".conf");
        args.append("-l");    // logfile (we get content with tail process)
        args.append(tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log");
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("racoon: " + GlobalConfig->pathToRacoon + " -f " + tmpPath + "/racoon." + GlobalConfig->currentProfile->getName() + ".conf", KVpncEnum::debug);

        //RacoonProcess->setProcessChannelMode( QProcess::MergedChannels );
        //RacoonProcess->closeStdin();
        connect(RacoonProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_racoon()));
        connect(RacoonProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_racoon()));

        RacoonProcess->setEnvironment(*env);
        RacoonProcess->start(proc, args);
        if (!RacoonProcess->waitForStarted()) {
            disconnect(RacoonProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_racoon()));
            disconnect(RacoonProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_racoon()));
            delete RacoonProcess;
            RacoonProcess = 0L;

            KMessageBox::error(this, i18n("Failed to start \"%1\"."  , QString("racoon")));
            GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString("racoon")) , KVpncEnum::error);
            disconnectClicked();
        } else {
            racoon_tunnel_state = 0;

            if (GlobalConfig->RacoonDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("%1 started. " , QString("racoon")), KVpncEnum::info);

            doTailRacoonLog();
            sleep(3);
            racoonStarted();

            //   sec = hour = min = 0;

            //    GlobalConfig->status = KVpncEnum::disconnected;
            //    timer.stop();
            //   connect( &durationTimer, SIGNAL( timeout() ), this, SLOT( slotDurationEvent() ) );
            //   durationTimer.start( 1000);
        }
    } else {
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("[racoon]: " + i18n("%1 finished with error." , QString("setkey")), KVpncEnum::debug);

    }
    delete RacoonHelperProcess;
    RacoonHelperProcess = 0L;
}

void KVpnc::stopRacoon()
{
    if (GlobalConfig->KvpncDebugLevel > 2)
        GlobalConfig->appendLogEntry(i18n("Stopping %1." , QString("racoon")), KVpncEnum::debug);

    putenv((char*)("LC_ALL=C"));
    RacoonctlProcess = new QProcess(this);
    QString PathToRacoonctl = "";
    ToolInfo* Tool = Utils(GlobalConfig).getToolInfo("racoonctl");
    PathToRacoonctl = Tool->PathToExec;

    QString proc = PathToRacoonctl;
    QStringList args;
    args.append("vpn-disconnect");

    args.append(GlobalConfig->TmpGatewayIP);

    connect(RacoonctlProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_racoonctl()));
    connect(RacoonctlProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_racoonctl()));
    connect(RacoonctlProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(racoonctlExited(int, QProcess::ExitStatus)));

    RacoonctlProcess->setEnvironment(*env);
    RacoonctlProcess->start(proc, args);
    if (!RacoonctlProcess->waitForStarted())
        KMessageBox::error(this, i18n("Failed to start \"%1\"."  , QString(QString("racoonctl vpn-disconnect " + GlobalConfig->TmpGatewayIP))));
    else {
        if (GlobalConfig->KvpncDebugLevel > 2)
            GlobalConfig->appendLogEntry(i18n("%1 started. " , QString(QString("racoonctl vpn-disconnect " + GlobalConfig->TmpGatewayIP))), KVpncEnum::info);

        waitForFinished(RacoonctlProcess, 100);
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("\"%1\" finished."  , QString(QString("racoonctl vpn-disconnect " + GlobalConfig->TmpGatewayIP))), KVpncEnum::debug);
    }
    disconnect(RacoonctlProcess, SIGNAL(readyReadStdout()), this, SLOT(readFromStdout_racoonctl()));
    disconnect(RacoonctlProcess, SIGNAL(readyReadStderr()), this, SLOT(readFromStderr_racoonctl()));
    disconnect(RacoonctlProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(racoonctlExited(int, QProcess::ExitStatus)));
    delete RacoonctlProcess;
    RacoonctlProcess = 0L;
}

void KVpnc::doTailRacoonLog()
{
    putenv((char*)("LC_ALL=C"));
    RacoonTailProcess = new QProcess(this);
    QString proc = GlobalConfig->pathToTail;
    QStringList args;
    args.append("-n");
    args.append("1000");
    args.append("-f");
    args.append(tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log");

    connect(RacoonTailProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_tail_racoon()));
    connect(RacoonTailProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_tail_racoon()));

    RacoonTailProcess->setEnvironment(*env);
    RacoonTailProcess->start(proc, args);
    if (!RacoonTailProcess->waitForStarted()) {
        disconnect(RacoonTailProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_tail_racoon()));
        disconnect(RacoonTailProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_tail_racoon()));
        delete RacoonTailProcess;
        RacoonTailProcess = 0L;

        KMessageBox::error(this, i18n("Failed to start \"%1\"."  , QString(GlobalConfig->pathToTail + " -f " + tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log")));
        GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString(GlobalConfig->pathToTail + " -f " + tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log")) , KVpncEnum::error);
        disconnectClicked();
    } else {
        //         status=connected;
        //         setGuiStatus(KVpncEnum::connected);

        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("\"%1\" started."  , QString(GlobalConfig->pathToTail + " -f " + tmpPath + "racoon." + GlobalConfig->currentProfile->getName() + ".log")), KVpncEnum::debug);


    }

}

void KVpnc::removeIptablesRacoon()
{
    putenv((char*)("LC_ALL=C"));
    QProcess RemoveIptablesRacoonProcess(this);
    QString proc = GlobalConfig->InterpreterShell;
    QStringList args;
    args.append(tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".remove_racoon.sh");
    RemoveIptablesRacoonProcess.setEnvironment(*env);
    RemoveIptablesRacoonProcess.start(proc, args);
    if (!RemoveIptablesRacoonProcess.waitForStarted()) {
        KMessageBox::error(this, i18n("Failed to start \"%1\"."  , QString("iptables." + GlobalConfig->currentProfile->getName() + ".remove_racoon.sh")));
        GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString("iptables." + GlobalConfig->currentProfile->getName() + ".remove_racoon.sh")), KVpncEnum::error);
        disconnectClicked();
    } else {
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("\"%1\" started."  , QString("iptables." + GlobalConfig->currentProfile->getName() + ".remove_racoon.sh")), KVpncEnum::debug);
        waitForFinished(&RemoveIptablesRacoonProcess, 100);
    }
}

void KVpnc::removeSetkey()
{

    putenv((char*)("LC_ALL=C"));
    QProcess RemoveSetkeyProcess(this);
    QString proc = GlobalConfig->InterpreterShell;
    QStringList args;
    args.append(tmpPath + "setkey." + GlobalConfig->currentProfile->getName() + ".remove_setkey.sh");

    RemoveSetkeyProcess.start(proc, args);
    if (!RemoveSetkeyProcess.waitForStarted()) {
        //   KMessageBox::error( this, i18n( "Failed to start \"%1\"."  , QString("setkey (remove)" ) ));
        GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString("setkey (remove)")) , KVpncEnum::error);
    } else {
        if (GlobalConfig->KvpncDebugLevel > 1)
            GlobalConfig->appendLogEntry(i18n("\"%1\" started."  , QString("setkey (remove)")), KVpncEnum::debug);
        waitForFinished(&RemoveSetkeyProcess, 100);
        if (GlobalConfig->KvpncDebugLevel > 1)
            GlobalConfig->appendLogEntry(i18n("\"%1\" finished."  , QString("setkey (remove)")), KVpncEnum::debug);

    }
    //  connectionEnded();
}

void KVpnc::doIptablesFreeswan()
{
    //  if ( ConnectProcess->normalExit () )
    {
        /*
        iptables -I INPUT -p 50 -i $IFACE -s $VPNGW_IP -j ACCEPT
        */
        putenv((char*)("LC_ALL=C"));
        QProcess IptablesFreeswanProcess(this);
        QString proc = GlobalConfig->InterpreterShell;
        QStringList args;
        args.append(tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".add_ipsec_freeswan.sh");
        IptablesFreeswanProcess.setEnvironment(*env);
        IptablesFreeswanProcess.start(proc, args);
        if (!IptablesFreeswanProcess.waitForStarted()) {
            KMessageBox::error(this, i18n("Failed to start \"%1\"."  , QString("iptables." + GlobalConfig->currentProfile->getName() + ".add_ipsec_freeswan.sh")));
            GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString("iptables." + GlobalConfig->currentProfile->getName() + ".add_ipsec_freeswan.sh")) , KVpncEnum::error);
            disconnectClicked();
        } else {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("\"%1\" started."  , QString(i18n("iptables.%1.add_ipsec_freeswan.sh" , GlobalConfig->currentProfile->getName()))), KVpncEnum::debug);

            setFirewallAfterConnect();
            if (GlobalConfig->currentProfile->getExecuteCmdAfterConnect())
                executeCommandAfterConnect();
            waitForFinished(&IptablesFreeswanProcess, 100);
        }
    }
}

void KVpnc::addRouteIpsec()
{
    tmpPath = KStandardDirs::locateLocal("data", "kvpnc/");
    QString IpsecRouteSetScript = tmpPath + "/set_route." + GlobalConfig->currentProfile->getName() + ".sh";
    NetworkInterface iface(GlobalConfig, parent);
    QString defaultinterface = iface.getDefaultInterface();
    QString dev = "lo";

    QString RemoteNetAddr = GlobalConfig->currentProfile->getRemoteNetAddr();
    QString RemoteNetMask = GlobalConfig->currentProfile->getRemoteNetMask();
    QString RemoteNet = RemoteNetAddr + "/" + RemoteNetMask;

    if (iface.interfaceExist("ipsec0"))
        tmpInterface = "ipsec0";
    else
        tmpInterface = iface.getDefaultInterface();

    if (GlobalConfig->currentProfile->getUseVirtualIP())
        dev = QString(dev + ":100");
    else
        dev = tmpInterface;

    QFile IpsecSetRouteScript(IpsecRouteSetScript);
    QTextStream stream(&IpsecSetRouteScript);
    if (IpsecSetRouteScript.open(QIODevice::WriteOnly)) {
        if (GlobalConfig->currentProfile->getReplaceDefaultRoute()) {
            stream << GlobalConfig->pathToIp << " route show  | grep 'default via' > " + tmpPath + "default-route." + GlobalConfig->currentProfile->getName() << "\n";
            stream << GlobalConfig->pathToRoute << " del default" << "\n";

            stream << GlobalConfig->pathToRoute << " add default gw " << GlobalConfig->currentProfile->getGateway() << " " << iface.getDefaultInterface() << "\n";
        }
        //      stream << GlobalConfig->pathToRoute << " add -net " << RemoteNet << " " << dev << "\n"; // set by opnswan
        IpsecSetRouteScript.close();

        RouteProcess = new QProcess(this);
        QString proc = GlobalConfig->InterpreterShell;
        QStringList args;
        args.append(IpsecRouteSetScript);

        connect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_route()));
        connect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_route()));
        RouteProcess->setEnvironment(*env);
        RouteProcess->start(proc, args);
        if (!RouteProcess->waitForStarted()) {
            KMessageBox::error(this, i18n("Failed to start \"%1\"."  , QString("route (%1)") , QString(IpsecType)));
            GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString("route (%1)")  , QString(IpsecType)) , KVpncEnum::error);
            //    disconnectClicked();
        } else {
            if (GlobalConfig->KvpncDebugLevel > 0) {
                if (GlobalConfig->currentProfile->getReplaceDefaultRoute())
                    GlobalConfig->appendLogEntry(i18n("route (%1): route add default gw "  , QString("ipsec"  + GlobalConfig->currentProfile->getGateway() + " " + tmpInterface)), KVpncEnum::debug);
                //        GlobalConfig->appendLogEntry ( i18n( "route (%1): route add -net "  , QString("ipsec" + RemoteNet << " " + tmpInterface), KVpncEnum::debug );
                disconnect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_route()));
                disconnect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_route()));
                delete RouteProcess;
                RouteProcess = 0L;
                return;
            }
            waitForFinished(RouteProcess, 100);
            disconnect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_route()));
            disconnect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_route()));
            delete RouteProcess;
            RouteProcess = 0L;
        }

    }
}

void KVpnc::delRouteIpsec()
{
    tmpPath = KStandardDirs::locateLocal("data", "kvpnc/");
    QString IpsecRouteSetScript = tmpPath + "/remove_route." + GlobalConfig->currentProfile->getName() + ".sh";
    NetworkInterface iface(GlobalConfig, parent);
    QString dev = "lo";

    QString RemoteNetAddr = GlobalConfig->currentProfile->getRemoteNetAddr();
    QString RemoteNetMask = GlobalConfig->currentProfile->getRemoteNetMask();
    QString RemoteNet = RemoteNetAddr + "/" + RemoteNetMask;

    if (iface.interfaceExist("ipsec0"))
        tmpInterface = "ipsec0";
    else
        tmpInterface = iface.getDefaultInterface();

    if (GlobalConfig->currentProfile->getUseVirtualIP())
        dev = QString(dev + ":100");
    else
        dev = tmpInterface;

    QFile IpsecSetRouteScript(IpsecRouteSetScript);
    QTextStream stream(&IpsecSetRouteScript);
    if (IpsecSetRouteScript.open(QIODevice::WriteOnly)) {
        stream <<  "#!" << GlobalConfig->InterpreterShell << "\n";
        if (GlobalConfig->currentProfile->getReplaceDefaultRoute()) {
            stream << GlobalConfig->pathToRoute << " del default" << "\n";

            stream << GlobalConfig->pathToIp << " route add `cat " + tmpPath + "default-route." + GlobalConfig->currentProfile->getName() << "`" << "\n";
        }

        if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan)
            stream << GlobalConfig->pathToRoute << " del -net " << RemoteNet << " " << dev << "\n";
        IpsecSetRouteScript.close();

        RouteProcess = new QProcess(this);
        QString proc = GlobalConfig->InterpreterShell;
        QStringList args;
        args.append(IpsecRouteSetScript);

        connect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_route()));
        connect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStderr_route()));

        RouteProcess->setEnvironment(*env);
        RouteProcess->start(proc, args);
        if (!RouteProcess->waitForStarted()) {
            //    KMessageBox::error( this, i18n( "Failed to start \"%1\"."  , QString( "del route ("+IpsecType+")" ) ));
            GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString("del route (" + IpsecType + ")")) , KVpncEnum::error);
            disconnect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_route()));
            disconnect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStderr_route()));
            delete RouteProcess;
            RouteProcess = 0L;
        } else {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("route (ipsec): route del started."), KVpncEnum::debug);
            waitForFinished(RouteProcess, 100);
            disconnect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_route()));
            disconnect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_route()));
            delete RouteProcess;
            RouteProcess = 0L;
        }

    }
}

void KVpnc::removeIptablesFreeswan()
{
    putenv((char*)("LC_ALL=C"));
    QProcess RemoveIptablesFreeswanProcess(this);
    QString proc = GlobalConfig->InterpreterShell;
    QStringList args;
    args.append(tmpPath + "iptables." + GlobalConfig->currentProfile->getName() + ".remove_ipsec_freeswan.sh");
    RemoveIptablesFreeswanProcess.setEnvironment(*env);
    RemoveIptablesFreeswanProcess.start(proc, args);
    if (!RemoveIptablesFreeswanProcess.waitForStarted()) {
        //    KMessageBox::error( this, i18n( "Failed to start \"%1\"."  , QString( "iptables." + GlobalConfig->currentProfile->getName() + ".remove_ipsec_freeswan.sh" )) );
        GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString("iptables." + GlobalConfig->currentProfile->getName() + ".remove_ipsec_freeswan.sh")), KVpncEnum::error);
    } else {
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("\"%1\" started."  , QString("iptables." + GlobalConfig->currentProfile->getName() + ".remove_ipsec_freeswan.sh")), KVpncEnum::debug);
        waitForFinished(&RemoveIptablesFreeswanProcess, 100);
    }

}

void KVpnc::doPingTest()
{
    /*
    ping -c3 -I <interfaceIP> <gateway>
    */
    QString LocalIP;
    QString Interface;
    NetworkInterface iface(GlobalConfig, parent);
    //LocalIP = iface.getInterfaceIP( iface.getDefaultInterface() );
    if (GlobalConfig->currentProfile->getNetworkDevice().isEmpty())
        Interface = iface.getInterfaceIP(iface.getDefaultInterface());
    else
        Interface = GlobalConfig->currentProfile->getNetworkDevice();
    QString PingHostIP = GlobalConfig->currentProfile->getPingHostIP();
    if (GlobalConfig->KvpncDebugLevel > 0)
        GlobalConfig->appendLogEntry(i18n("Hostname/IP address for ping: %1"  , QString(PingHostIP)), KVpncEnum::debug);

    /* first: kick up the tunnel */
    putenv((char*)("LC_ALL=C"));
    PingProcess = new QProcess(this);

    QString PathToPing = "";
    ToolInfo *Tool=0L;
    for (int toolIdx = 0; toolIdx < GlobalConfig->ToolList->size(); ++toolIdx) {
        Tool = GlobalConfig->ToolList->at(toolIdx);
        if (Tool->Name == "ping") {
            PathToPing = Tool->PathToExec;
            break;
        }
    }
    QString proc = PathToPing;
    QStringList args;
    args.append("-c1");
    args.append(PingHostIP);
    PingProcess->setEnvironment(*env);
    PingProcess->start(proc, args);
    if (!PingProcess->waitForStarted()) {
        KMessageBox::error(this, i18n("Failed to start \"%1\"."  , QString("ping " + GlobalConfig->currentProfile->getPingHostIP())));
        GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString("ping " + GlobalConfig->currentProfile->getPingHostIP())), KVpncEnum::error);
    } else {
        sleep(1);
        if (PingProcess->state() == QProcess::Running)
            PingProcess->kill();
        /* second: real ping */
        args.clear();
        args.append("-c5");
        args.append("-v");
        //args.append( "-I" );
        //args.append( Interface );
        args.append(PingHostIP);

        connect(PingProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ping()));
        connect(PingProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ping()));
        connect(PingProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(pingTestExited(int, QProcess::ExitStatus)));

        pingtest = true;
        PingProcess->setEnvironment(*env);
        PingProcess->start(proc, args);
        if (!PingProcess->waitForStarted()) {
            KMessageBox::error(this, i18n("Failed to start \"%1\"."  , QString("ping " + GlobalConfig->currentProfile->getPingHostIP())));
            GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString("ping " + GlobalConfig->currentProfile->getPingHostIP())) , KVpncEnum::error);
        } else {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("\"%1\" started."  , QString("ping")), KVpncEnum::debug);
            //sleep(5);
//             PingProcess->kill();
//             PingProcess->start(env);
            waitForFinished(PingProcess, 100);
        }
        disconnect(PingProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ping()));
        disconnect(PingProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ping()));
        disconnect(PingProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(pingTestExited(int, QProcess::ExitStatus)));
        delete PingProcess;
        PingProcess = 0L;
    }
}

void KVpnc::pingTestExited(int, QProcess::ExitStatus)
{
    //     disconnect(PingProcess, SIGNAL(finished ( int, QProcess::ExitStatus )), this, SLOT(pingTestExited(int, QProcess::ExitStatus)));
    //  disconnect( PingProcess, SIGNAL( readyReadStandardOutput() ), this, SLOT( readFromStdout_ping() ) );
    //  disconnect( PingProcess, SIGNAL( readyReadStandardError() ), this, SLOT( readFromStderr_ping() ) );
    // pingtest = false;
}

void KVpnc::vpncStarted()
{
    GlobalConfig->appendLogEntry(i18n("Vpnc has started"), KVpncEnum::debug);
    disconnect(VpncProcess, SIGNAL(started()), this, SLOT(vpncStarted()));

    if (!VpncProcess->waitForStarted()) {
        KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , QString("vpnc")));
        GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("vpnc")), KVpncEnum::error);
        disconnectClicked();
        setGuiStatus(KVpncEnum::disconnected);
    }
    //     if ( VpncProcess->state() == KPtyProcess::Running) {
    else {
        slotStatusMsg(i18n("Connecting..."), ID_CONNECTION_MSG);
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString("vpnc")), KVpncEnum::debug);
        ConnectingProcess = VpnAccountData::cisco;
        GlobalConfig->status = KVpncEnum::connecting;
        mw->buttonDisconnect->setEnabled(true);
        DisconnectAction->setEnabled(true);
        mw->buttonConnect->setEnabled(false);
        ConnectAction->setEnabled(false);


        disconnect(&timer, SIGNAL(timeout()), this, SLOT(slotConnectTimedOut()));
        connect(&timer, SIGNAL(timeout()), this, SLOT(slotConnectTimedOut()));
        timer.start(GlobalConfig->tryConnectTimeout * 1000);

        if (VpncProcess->state() == QProcess::Running) {
            // define 0.2.1
            int vpnc_version_major = 0;
            int vpnc_version_minor = 2;
            int vpnc_version_subminor = 1;

            ToolInfo *Tool = Utils(GlobalConfig).getToolInfo("vpnc");
            if (!Tool->Version.isEmpty()) {
                vpnc_version_major = (Tool->Version.section('.', 0, 0)).toInt();
                vpnc_version_minor = (Tool->Version.section('.', 1, 1)).toInt();
                vpnc_version_subminor = (Tool->Version.section('.', 2, 2)).toInt();
                if (GlobalConfig->KvpncDebugLevel > 0) {
                    GlobalConfig->appendLogEntry(i18n("vpnc version (major): \"%1\"" , vpnc_version_major) , KVpncEnum::debug);
                    GlobalConfig->appendLogEntry(i18n("vpnc version (minor): \"%1\"" , vpnc_version_minor) , KVpncEnum::debug);
                    GlobalConfig->appendLogEntry(i18n("vpnc version (subminor): \"%1\"" , vpnc_version_subminor) , KVpncEnum::debug);
                }
            }
            bool doWrite = false;
// 			   if (vpnc_version_major >= 0 && vpnc_version_minor > 2) {
// 			    if (vpnc_version_minor > 3) {
// 			     doWrite = true;
// 			    } else {
// 			      if (vpnc_version_subminor > 2) {
// 			       doWrite = true;
// 			     }
// 			    }
// 			   }

            if (doWrite) {
                // we send config via stdin

// 				// sleep 3s
// 				for (int i=0;i< 3; i++) {
// 						sleep(1);
// 						if (GlobalConfig->appPointer->hasPendingEvents())
// 							GlobalConfig->appPointer->processEvents();
// 				}

                if (GlobalConfig->KvpncDebugLevel > 2)
                    GlobalConfig->appendLogEntry(i18n("Sending config to \"%1\"..." , QString("vpnc")), KVpncEnum::debug);

                sendingVpncConfigInProgress = true;
                VpncPty->write(vpncConfig.toUtf8());
                //VpncProcess->write(vpncConfig.toUtf8());
                sendingVpncConfigInProgress = false;

                if (GlobalConfig->KvpncDebugLevel > 2)
                    GlobalConfig->appendLogEntry(i18n("Config to \"%1\" sent." , QString("vpnc")), KVpncEnum::debug);

            }
        }
    }

}

void KVpnc::racoonStarted()
{

    if (GlobalConfig->KvpncDebugLevel > 0)
        GlobalConfig->appendLogEntry(i18n("Policy was successful activated and daemon (%1) is running, starting up tunnel..."  , QString("racoon")), KVpncEnum::debug);

    bool AdminSockExist = false;
    int tryCounter = 0;
    while (!AdminSockExist && tryCounter < 20) {
        AdminSockExist = QFile("/var/run/racoon/racoon.sock").exists();
        tryCounter++;
        if (tryCounter == 20)
            break;
        else {
            tryCounter = 0;
            if (GlobalConfig->KvpncDebugLevel > 8) {
                GlobalConfig->appendLogEntry(i18n("Waiting admin sock of %1..."  , QString("racoon")), KVpncEnum::debug);
            }
        }
        usleep(100);
        GlobalConfig->appPointer->processEvents();
    }

    if (tryCounter == 20) {
        GlobalConfig->appendLogEntry(i18n("Waiting admin sock of %1 needs too long. Stop."  , QString("racoon")), KVpncEnum::debug);
        disconnectClicked();
        return;
    }

    putenv((char*)("LC_ALL=C"));
    RacoonctlProcess = new QProcess(this);
    QString PathToRacoonctl = "";
    ToolInfo* Tool = Utils(GlobalConfig).getToolInfo("racoonctl");
    PathToRacoonctl = Tool->PathToExec;

    QString proc = PathToRacoonctl;
    QStringList args;
    args.append("vpn-connect");

    if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()) {
        args.append("-u");
        args.append(GlobalConfig->TmpUsername);
    }

    args.append(GlobalConfig->TmpGatewayIP);

    connect(RacoonctlProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_racoonctl()));
    connect(RacoonctlProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_racoonctl()));
    connect(RacoonctlProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(racoonctlExited(int, QProcess::ExitStatus)));

    RacoonctlProcess->setEnvironment(*env);
    RacoonctlProcess->start(proc, args);
    if (!RacoonctlProcess->waitForStarted()) {
        if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())
            KMessageBox::error(this, i18n("Failed to start \"%1\"."  , QString("racoonctl vpn-connect -u " + GlobalConfig->TmpUsername + " " + GlobalConfig->TmpGatewayIP)));
        else
            KMessageBox::error(this, i18n("Failed to start \"%1\"." , QString("racoonctl vpn-connect " + GlobalConfig->TmpGatewayIP)));
    } else {
        if (GlobalConfig->KvpncDebugLevel > 0) {
            if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword())
                GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString("racoonctl vpn-connect -u " + GlobalConfig->TmpUsername + " " + GlobalConfig->TmpGatewayIP)), KVpncEnum::debug);
            else
                GlobalConfig->appendLogEntry(i18n("\"%1\" started.", QString("racoonctl vpn-connect " + GlobalConfig->TmpGatewayIP)), KVpncEnum::debug);
        }

        if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()) {
//    for (int waitforconnect=0;waitforconnect< 25;waitforconnect++)
//     usleep(500);

//    sleep(10);
            if (GlobalConfig->VpncDebugLevel > 0)
                GlobalConfig->appendLogEntry("[racoonctl] " + i18n("User password requested, send it...\n"), KVpncEnum::debug);

            QString UserPassStr = "";
            if (!GlobalConfig->currentProfile->getSaveUserPassword() || AuthRetry)
                UserPassStr = GlobalConfig->TmpPassword;
            else
                UserPassStr = GlobalConfig->currentProfile->getUserPassword();

            if (GlobalConfig->KvpncDebugLevel > 8)
                GlobalConfig->appendLogEntry("[racoonctl] " + i18n("User password: %1\n"  , QString(UserPassStr)), KVpncEnum::debug);


            RacoonctlProcess->write(UserPassStr.toUtf8());
            RacoonctlProcess->write("\n");
        }

        int tryCounter=0;
        while (RacoonctlProcess->state() == QProcess::Running) {
            if ( tryCounter == 20 ) {
                tryCounter=0;
                if ( GlobalConfig->KvpncDebugLevel > 8 )
                    GlobalConfig->appendLogEntry ( i18n ( "\"%1\" is still running waiting for terminate..." , GlobalConfig->pathToRacoonctl ), KVpncEnum::debug );
            }
            if (GlobalConfig->appPointer->hasPendingEvents())
                GlobalConfig->appPointer->processEvents();
            usleep ( 500 );
        }

        disconnect(RacoonctlProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_racoonctl()));
        disconnect(RacoonctlProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_racoonctl()));
        disconnect(RacoonctlProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(racoonctlExited(int, QProcess::ExitStatus)));
        delete RacoonctlProcess;
        RacoonctlProcess = 0L;
    }

    //   else
    //   {
    //    //    disconnectClicked();
    //   }
    //   GlobalConfig->appendLogEntry( "[racoon] " + i18n( "Connection established." ), KVpncEnum::success );
    //
    //   sec = hour = min = 0;
    //
    //   GlobalConfig->status = KVpncEnum::connected;
    //
    //   connect( &durationTimer, SIGNAL( timeout() ), this, SLOT( slotDurationEvent() ) );
    //   durationTimer.start( 1000);
    //   setGuiStatus( connected );
    //
    //  setFirewallAfterConnect();
    //   if ( GlobalConfig->currentProfile->getExecuteCmdAfterConnect() )
    //    executeCommandAfterConnect();
    //
    //   if ( GlobalConfig->currentProfile->getUseAdditionalNetworkRoutes() && !GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty() )
    //    addAdditionalNetworkRoutes();
    //
    //   if ( GlobalConfig->currentProfile->getUseConnectionStatusCheck() ) {
    //    startConnectionStatusCheck();
    //   }
}

void KVpnc::ipsecStarted(int, QProcess::ExitStatus)
{
//  disconnect(IpsecProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(ipsecStarted(int, QProcess::ExitStatus)));
    disconnect(IpsecStartProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsec()));
    disconnect(IpsecStartProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsec()));
    delete IpsecStartProcess;
    IpsecStartProcess = 0L;

//  ToolInfo *IpsecToolInfo = Utils ( GlobalConfig ).getToolInfo ( "ipsec" ) ;

//  if ( GlobalConfig->KvpncDebugLevel > 0 )
//   GlobalConfig->appendLogEntry ( "[ipsec] " + i18n ( "Starting connection \"%1\"..."  , QString( GlobalConfig->currentProfile->getName() )) , KVpncEnum::debug );

//  /* Kick up the connection */
//  IpsecProcess = new QProcess( this );
//  QString proc = GlobalConfig->pathToIpsec;
//  QStringList args;
//  args.append ( "auto" );
//  //  if ( GlobalConfig->enableFreeswanVerbose )
//  //   args.append( "--verbose" );
//  args.append ( "--up" );
//  args.append ( GlobalConfig->currentProfile->getName() );
//
//
//  connect ( IpsecStartProcess, SIGNAL ( readyReadStandardOutput() ), this, SLOT ( readFromStderr_ipsec() ) );
//  connect ( IpsecStartProcess, SIGNAL ( readyReadStandardError() ), this, SLOT ( readFromStderr_ipsec() ) );
//  //    connect( IpsecStartProcess, SIGNAL( finished (int, QProcess::ExitStatus) ), this, SLOT( doRouteFreeswan(int, QProcess::ExitStatus) ) );
//
//  IpsecStartProcess->setEnvironment(*env);
//  IpsecStartProcess->start(proc,args);
//  if ( !IpsecStartProcess->waitForStarted() )
//  {
//   KMessageBox::error ( this, i18n ( "Failed to start \"%1\"."  , QString( "ipsec: connection" )) );
//   GlobalConfig->appendLogEntry ( i18n ( "Failed to start \"%1\"."  , QString( "ipsec: connection" )) , KVpncEnum::error );
//   //   disconnectClicked();
//  }
//  else
//  {
//   if ( GlobalConfig->KvpncDebugLevel > 2 )
//    GlobalConfig->appendLogEntry ( i18n ( "\"%1\" started."  , QString( "ipsec: connection" )) , KVpncEnum::debug );
// IpsecProcess->waitForFinished();
//  disconnect ( IpsecStartProcess, SIGNAL ( readyReadStandardOutput() ), this, SLOT ( readFromStderr_ipsec() ) );
//  disconnect ( IpsecStartProcess, SIGNAL ( readyReadStandardError() ), this, SLOT ( readFromStderr_ipsec() ) );
// delete IpsecProcess;
// IpsecProcess=0L;
//  }

    IpsecStatusCheck = true;
    checkIpsecWhackStatus();
    IpsecStatusCheck = false;

    if (GlobalConfig->KvpncDebugLevel > 0)
        GlobalConfig->appendLogEntry("[ipsec] " + i18n("Starting \"%1\"..."  , QString(GlobalConfig->pathToIpsec + " whack' --listen")) , KVpncEnum::debug);


    connectCounter = 0;
    sleep(1);
    putenv((char*)("LC_ALL=C"));
    IpsecWhackListenProcess = new QProcess(this);
    QString proc = GlobalConfig->pathToIpsec;
    QStringList args;
    args.append("whack");
    args.append("--listen");

    connect(IpsecWhackListenProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhacklisten()));
    connect(IpsecWhackListenProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhacklisten()));

    IpsecWhackListenProcess->setEnvironment(*env);
    IpsecWhackListenProcess->start(proc, args);
    if (!IpsecWhackListenProcess->waitForStarted()) {
        KMessageBox::error(this, i18n("Failed to start \"%1\"."  , QString(GlobalConfig->pathToIpsec + " whack' --listen")));
        GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString(GlobalConfig->pathToIpsec + " whack' --listen")) , KVpncEnum::error);
        disconnectClicked();
    } else {
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("\"%1\" started."  , QString(GlobalConfig->pathToIpsec + " whack  --listen")), KVpncEnum::debug);
    }

}

void KVpnc::checkIpsecWhackStatus()
{

    putenv((char*)("LC_ALL=C"));
    IpsecWhackStatusProcess = new QProcess(this);
    QString proc = GlobalConfig->pathToIpsec;
    QStringList args;

    args.append("whack");
    args.append("--status");
    disconnect(IpsecWhackStatusProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhackstatus()));
    disconnect(IpsecWhackStatusProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhackstatus()));
    connect(IpsecWhackStatusProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhackstatus()));
    connect(IpsecWhackStatusProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhackstatus()));
    connect(IpsecWhackStatusProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(IpsecWhackStatusProcessExited(int, QProcess::ExitStatus)));

    IpsecWhackStatusProcess->setEnvironment(*env);
    IpsecWhackStatusProcess->start(proc, args);
    if (!IpsecWhackStatusProcess->waitForStarted()) {
        disconnect(IpsecWhackStatusProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhackstatus()));
        disconnect(IpsecWhackStatusProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhackstatus()));
        disconnect(IpsecWhackStatusProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(IpsecWhackStatusProcessExited(int, QProcess::ExitStatus)));
        delete IpsecWhackStatusProcess;
        IpsecWhackStatusProcess = 0L;
        if (IpsecStatusCheck == false && IpsecPhase2Up == false) {
            KMessageBox::error(this, i18n("Failed to start \"%1\"."  , QString(GlobalConfig->pathToIpsec + " whack' --status")));
            GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString(GlobalConfig->pathToIpsec + " whack' --status")) , KVpncEnum::error);
            disconnectClicked();
        }
    } else {
        if (GlobalConfig->KvpncDebugLevel > 5)
            GlobalConfig->appendLogEntry(i18n("\"%1\" started."  , QString(GlobalConfig->pathToIpsec + " whack  --status")), KVpncEnum::debug);
        if (IpsecStatusCheck == true && IpsecPhase2Up == false) {
            if (!timer.isActive()) {
                disconnect(&timer, SIGNAL(timeout()), this, SLOT(slotConnectTimedOut()));
                connect(&timer, SIGNAL(timeout()), this, SLOT(slotConnectTimedOut()));
                // FIXME make connect timeout value in GUI available
                timer.start(2000 * 1000);
            }
            if (!IpsecWhackStatusTimer.isActive()) {
                disconnect(&IpsecWhackStatusTimer, SIGNAL(timeout()), this, SLOT(checkIpsecWhackStatus()));
                connect(&IpsecWhackStatusTimer, SIGNAL(timeout()), this, SLOT(checkIpsecWhackStatus()));
                IpsecWhackStatusTimer.start(5 * 1000);
            }
        }
    }
}

void KVpnc::startStopIpsec(bool stop, bool silent)
{

    ToolInfo *IpsecToolInfo = Utils(GlobalConfig).getToolInfo("ipsec") ;

    // FIXME replace with StartStopIpsecProcess
    IpsecStartProcess = new QProcess(this);
    QString proc = GlobalConfig->pathToIpsec;
    QStringList args;

    if (IpsecToolInfo->Version.contains("Openswan", Qt::CaseInsensitive))
        args.append("setup");

    if (stop == false) {
        if (silent == false || GlobalConfig->KvpncDebugLevel > 5) {
            if (IpsecToolInfo->Version.contains("strongSwan", Qt::CaseInsensitive) /*&&  ( (IpsecMajor >= 4 && IpsecMinor >= 2 && IpsecSubMinor >=2 ) || IpsecMajor > 4 )*/) {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry("[" + IpsecType + "] " + i18n("Starting %1..." , QString("openswan")), KVpncEnum::debug);
            }

            if (IpsecToolInfo->Version.contains("Openswan", Qt::CaseInsensitive)) {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry("[" + IpsecType + "] " + i18n("Starting %1..."  , QString("strongSwan")), KVpncEnum::debug);
            }
        }

        GlobalConfig->currentConnectRetry++;
        args.append("start");
    } else {
        if (silent == false || GlobalConfig->KvpncDebugLevel > 5) {
            if (IpsecToolInfo->Version.contains("strongSwan", Qt::CaseInsensitive) /*&&  ( (IpsecMajor >= 4 && IpsecMinor >= 2 && IpsecSubMinor >=2 ) || IpsecMajor > 4 )*/) {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry("[" + IpsecType + "] " + i18n("Stopping %1..."  , QString("openswan")), KVpncEnum::debug);
            }

            if (IpsecToolInfo->Version.contains("Openswan", Qt::CaseInsensitive)) {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry("[" + IpsecType + "] " + i18n("Stopping %1..."  , QString("strongSwan")), KVpncEnum::debug);
            }
        }
        args.append("stop");
    }

    if (silent == false || GlobalConfig->KvpncDebugLevel > 8) {
        connect(IpsecStartProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsec()));
        connect(IpsecStartProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsec()));
    }

    IpsecStartingInProgress = true;
    IpsecStartProcess->setEnvironment(*env);
    IpsecStartProcess->start(proc, args);
    if (!IpsecStartProcess->waitForStarted()) {
        if (silent == false) {
            KMessageBox::error(this, i18n("Failed to start \"%1\"."  , QString("ipsec")));
            GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString("ipsec")) , KVpncEnum::error);
        }
        IpsecStartingInProgress = false;
    } else {
        if (silent == false) {
            if (GlobalConfig->KvpncDebugLevel > 2)
                GlobalConfig->appendLogEntry(i18n("\"%1\" started."  , QString("ipsec")) , KVpncEnum::debug);
        }
        int currentConnectCounter = 0;
        while (currentConnectCounter < GlobalConfig->currentProfile->getMaxConnectTries() *1000 && IpsecStartProcess != 0L && IpsecStartProcess->state() == QProcess::Running) {
            if (silent == false) {
                if (GlobalConfig->KvpncDebugLevel > 8)
                    GlobalConfig->appendLogEntry(i18n("\"%1\" still running, waiting"  , QString("ipsec")) , KVpncEnum::debug);
            }
            currentConnectCounter++;
            usleep(200);
            if (GlobalConfig->appPointer->hasPendingEvents())
                GlobalConfig->appPointer->processEvents();

            if (currentConnectCounter > GlobalConfig->currentProfile->getMaxConnectTries() *1000) {
                if (silent == false) {
                    if (GlobalConfig->KvpncDebugLevel > 2)
                        GlobalConfig->appendLogEntry(i18n("\"%1\" still running but needs too long, stopping"  , QString("ipsec")) , KVpncEnum::debug);
                    if (silent == false || GlobalConfig->KvpncDebugLevel > 8) {
                        disconnect(IpsecStartProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsec()));
                        disconnect(IpsecStartProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsec()));
                    }
                    if (IpsecStartProcess != 0L)
                        IpsecStartProcess->kill();
                    disconnectClicked();
                    IpsecStartingInProgress = false;
                    return;
                }

            }
        }
        IpsecStartingInProgress = false;
    }
}

void KVpnc::addIpsecConnection()
{


}

void KVpnc::start_ipsec_initiate()
{
    // strongswan after ipsec whack --listen
    /*   disconnect ( IpsecWhackProcess, SIGNAL ( readyReadStandardOutput() ), this, SLOT ( readFromStdout_ipsecwhack() ) );
       disconnect ( IpsecWhackProcess, SIGNAL ( readyReadStandardError() ), this, SLOT ( readFromStderr_ipsecwhack() ) );
       delete IpsecWhackProcess;*/
    if ( IpsecGotError)
        return;

    sleep(4);

    putenv((char*)("LC_ALL=C"));
    IpsecWhackProcess = new QProcess(this);
    QString proc = GlobalConfig->pathToIpsec;
    QStringList args;
    args.append("whack");
    args.append("--name");
    args.append(GlobalConfig->currentProfile->getName());
    args.append("--initiate");

    connect(IpsecWhackProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhack()));
    connect(IpsecWhackProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhack()));
    connect(IpsecWhackProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(ipsecwhack_exited(int, QProcess::ExitStatus)));

    IpsecWhackProcess->setEnvironment(*env);
    IpsecWhackProcess->start(proc, args);
    if (!IpsecWhackProcess->waitForStarted()) {
        disconnect(IpsecWhackProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhack()));
        disconnect(IpsecWhackProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhack()));
        disconnect(IpsecWhackProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(ipsecwhack_exited(int, QProcess::ExitStatus)));
        delete IpsecWhackProcess;
        IpsecWhackProcess = 0L;
        KMessageBox::error(this, i18n("Failed to start \"%1\"." , QString(GlobalConfig->pathToIpsec + " whack' --name " + GlobalConfig->currentProfile->getName() + " --initiate")));
        GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString(GlobalConfig->pathToIpsec + " whack' --name " + GlobalConfig->currentProfile->getName() + " --initiate")) , KVpncEnum::error);
        disconnectClicked();
    } else {
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("\"%1\" started."  , QString(GlobalConfig->pathToIpsec + " whack --name " + GlobalConfig->currentProfile->getName() + " --initiate")), KVpncEnum::debug);

        if (!IpsecGotError)
            checkIpsecWhackStatus();
    }


}

void KVpnc::ipsecPhase2Established()
{
    if (IpsecPhase2Up)
        return;
    else {
        timer.stop();
        IpsecWhackStatusTimer.stop();

        // hack: if from status phase2 is first
        if (IpsecPhase1Up == false) {

            if (IpsecPhase1Up)
                return;
            else
                IpsecPhase1Up = true;

            if (IpsecPhase2Up)
                return;

            if (GlobalConfig->KvpncDebugLevel > 1) {
                if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan) {
                    GlobalConfig->appendLogEntry("[ipsec] " + i18n("IPSec phase 2 established."), KVpncEnum::info);
                } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
                    GlobalConfig->appendLogEntry("[ipsec] " + i18n("Low level IPsec phase 2 established."), KVpncEnum::info);
                }
            }

        }
        IpsecPhase2Up = true;
    }

    if (GlobalConfig->KvpncDebugLevel > 1) {
        if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan) {
            GlobalConfig->appendLogEntry("[ipsec] " + i18n("IPSec phase 2 established."), KVpncEnum::info);
        } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
            GlobalConfig->appendLogEntry("[ipsec] " + i18n("Low level IPsec phase 2 established."), KVpncEnum::info);
        }
    }

    doIptablesFreeswan();
    addRouteIpsec();

    if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan) {
        start_l2tpd();
    } else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan) {
        sec = hour = min = 0;

        GlobalConfig->status = KVpncEnum::connected;

        disconnect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));
        connect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));
        durationTimer.start(1000);
        setGuiStatus(KVpncEnum::connected);


        setFirewallAfterConnect();
        if (GlobalConfig->currentProfile->getExecuteCmdAfterConnect())
            executeCommandAfterConnect();

        if (GlobalConfig->currentProfile->getUseAdditionalNetworkRoutes() && !GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty())
            addAdditionalNetworkRoutes();

        if (GlobalConfig->currentProfile->getUseConnectionStatusCheck()) {
            startConnectionStatusCheck();
        }
    }

}

void KVpnc::doAddRemoveVirtualIp(QString vaction)
{
    if ( GlobalConfig->KvpncDebugLevel > 3 )
        GlobalConfig->appendLogEntry ( i18n ( "doAddRemoveVirtualIp() action: %1", vaction ), KVpncEnum::debug );

    QString ActionPretty=i18n("Adding");
    if (vaction =="del")
        ActionPretty=i18n("Removing");

    if ( GlobalConfig->KvpncDebugLevel > 4 )
        GlobalConfig->appendLogEntry ( i18n ( "%1 virtual IP (%2) and special route...", ActionPretty, GlobalConfig->currentProfile->getLeftSourceIp()), KVpncEnum::debug );

    // FIXME convert LeftSourceIp to Virtual IP

    QString tmpPath = KStandardDirs::locateLocal ( "data", "kvpnc/" );
    QString IpsecVirtualIpFilename = tmpPath+"do-"+vaction+"-"+GlobalConfig->currentProfile->getName()+".virtualip.sh";
    QFile virtualfile ( IpsecVirtualIpFilename );
    QTextStream stream ( &virtualfile );
    if ( virtualfile.open ( IO_WriteOnly ) )
    {
        stream <<  "#!"<< GlobalConfig->InterpreterShell << "\n";
        stream << "# generated by kvpnc. Do not edit it." << "\n";
        stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";
        stream << "" << "\n";

        NetworkInterface iface ( GlobalConfig, parent );
        if ( GlobalConfig->currentProfile->getNetworkDevice() == "default" || GlobalConfig->currentProfile->getNetworkDevice() == "" )
        {
            tmpInterface = iface.getDefaultInterface();
            if ( GlobalConfig->KvpncDebugLevel > 0 )
                GlobalConfig->appendLogEntry ( i18n ( "Default interface: \"%1\"." ).arg ( tmpInterface ) , KVpncEnum::debug );
            LocalIP = iface.getInterfaceIP ( iface.getDefaultInterface() );
            if ( GlobalConfig->KvpncDebugLevel > 0 )
                GlobalConfig->appendLogEntry ( i18n ( "IP address of default interface: \"%1\".", LocalIP ) , KVpncEnum::debug );
        }
        else
        {
            tmpInterface = GlobalConfig->currentProfile->getNetworkDevice();
            LocalIP = iface.getInterfaceIP ( GlobalConfig->currentProfile->getNetworkDevice() );
        }

        if ( GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan)
        {
            // fix bad route from *swan

            if (vaction == "add")
                stream << GlobalConfig->pathToIp << " route del " << GlobalConfig->currentProfile->getRemoteNetAddr() << "/" << GlobalConfig->currentProfile->getRemoteNetMask() << " src " << GlobalConfig->currentProfile->getLeftSourceIp() << " dev " << tmpInterface<< "\n";
            else
                stream << GlobalConfig->pathToIp << " route add " << GlobalConfig->currentProfile->getRemoteNetAddr() << "/" << GlobalConfig->currentProfile->getRemoteNetMask() << " src " << GlobalConfig->currentProfile->getLeftSourceIp() << " dev " << tmpInterface<< "\n";
        }

        stream << GlobalConfig->pathToIp << " addr "+vaction+" " << GlobalConfig->currentProfile->getLeftSourceIp() << "/32 dev " << tmpInterface << "\n";
        stream << GlobalConfig->pathToIp << " route "+vaction+" " << GlobalConfig->currentProfile->getRemoteNetAddr() << "/" << GlobalConfig->currentProfile->getRemoteNetMask() << " via " << GlobalConfig->currentProfile->getLeftSourceIp() << " dev " << tmpInterface<< "\n";


        virtualfile.close();
        QProcess *IpsecVirtualIpProcess = new QProcess();
        QStringList args;
        args.append ( IpsecVirtualIpFilename );
        IpsecVirtualIpProcess->setEnvironment(*env);
        IpsecVirtualIpProcess->start(GlobalConfig->InterpreterShell, args);
        if (!IpsecVirtualIpProcess->waitForStarted()) {
            KMessageBox::sorry ( this, i18n ( "\"%1\" (%2) start failed!", QString("VirtualIpScript" ), IpsecVirtualIpFilename ));
        }
        else
        {
            if ( GlobalConfig->KvpncDebugLevel > 2 )
                GlobalConfig->appendLogEntry ( i18n ( "\"%1\" (%2) started.", QString("VirtualIpScript"), IpsecVirtualIpFilename ) , KVpncEnum::debug );
            while ( IpsecVirtualIpProcess->state() == QProcess::Running ) {
                if (GlobalConfig->appPointer->hasPendingEvents())
                    GlobalConfig->appPointer->processEvents();
                usleep (250);
            }
            if ( GlobalConfig->KvpncDebugLevel > 2 )
                GlobalConfig->appendLogEntry ( i18n ( "\"%1\" (%2) finished.", QString ("VirtualIpScript" ), IpsecVirtualIpFilename ), KVpncEnum::debug );
        }
        delete IpsecVirtualIpProcess;
    }
    else
    {
        GlobalConfig->appendLogEntry ( i18n ( "%1 file could not be written.", QString("VirtualIpScript")), KVpncEnum::error );
    }

}

void KVpnc::pppdStarted(int, QProcess::ExitStatus)
{
    //  disconnect ( PptpProcess, SIGNAL( processExited (int, QProcess::ExitStatus) ), this, SLOT( pppdStarted(int, QProcess::ExitStatus) ) );
//  disconnect ( pppdUpProcess, SIGNAL ( finished (int, QProcess::ExitStatus) ), this, SLOT ( pppdStarted(int, QProcess::ExitStatus) ) );

//  if ( GlobalConfig->KvpncDebugLevel > 0 )
//   GlobalConfig->appendLogEntry ( i18n ( "\"%1\" finished."  , QString( "PppdUpScript" )), KVpncEnum::debug );

}

void KVpnc::openvpnStarted(int, QProcess::ExitStatus)
{
    disconnect(OpenvpnProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(openvpnStarted(int, QProcess::ExitStatus)));
}

void KVpnc::startStopOpenl2tp(bool stop, bool silent)
{

    if (GlobalConfig->KvpncDebugLevel > 0)
        GlobalConfig->appendLogEntry("[openl2tp] " + i18n("Starting %1..."  , QString("/etc/init.d/openl2tpd")) , KVpncEnum::debug);
    StartStopOpenl2tpProcess = new QProcess(this);
    QString proc = "/etc/init.d/openl2tp";
    QStringList args;

    if (stop == false) {
        if (silent == false || GlobalConfig->KvpncDebugLevel > 5) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Starting %1..."  , QString("openl2tpd")), KVpncEnum::debug);
        }
        args.append("start");
        GlobalConfig->currentConnectRetry++;
    } else {
        if (silent == false || GlobalConfig->KvpncDebugLevel > 5) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Stopping %1..."  , QString("openl2tp")), KVpncEnum::debug);
        }
        args.append("stop");
    }

    if (silent == false || GlobalConfig->KvpncDebugLevel > 8) {
        connect(StartStopOpenl2tpProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_startstopOpenl2tp()));
        connect(StartStopOpenl2tpProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_startstopOpenl2tp()));
    }

    IpsecStartingInProgress = true;
    StartStopOpenl2tpProcess->setEnvironment(*env);
    StartStopOpenl2tpProcess->start(proc, args);
    if (!StartStopOpenl2tpProcess->waitForStarted()) {
        if (silent == false) {
            KMessageBox::error(this, i18n("Failed to start \"%1\"."  , QString("ipsec")));
            GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString("ipsec")) , KVpncEnum::error);
        }
        //   disconnectClicked();
        StartStopOpenl2tpProcess->terminate();
        usleep(500);
        if (StartStopOpenl2tpProcess->state() == QProcess::Running)
            StartStopOpenl2tpProcess->kill();
        IpsecStartingInProgress = false;
    } else {
        if (silent == false) {
            if (GlobalConfig->KvpncDebugLevel > 2) {
                if (stop == false) {
                    GlobalConfig->appendLogEntry(i18n("\"%1\" started."  , QString("/etc/init.d/openl2tp start")) , KVpncEnum::debug);
                } else {
                    GlobalConfig->appendLogEntry(i18n("\"%1\" started."  , QString("/etc/init.d/openl2tp stop")) , KVpncEnum::debug);
                }
            }
        }
        int currentConnectCounter = 0;
        while (currentConnectCounter < GlobalConfig->currentProfile->getMaxConnectTries() *1000 && StartStopOpenl2tpProcess->state() == QProcess::Running) {
            if (silent == false) {
                if (GlobalConfig->KvpncDebugLevel > 8) {
                    if (stop == false)
                        GlobalConfig->appendLogEntry(i18n("\"%1\" still running, waiting"  , QString("/etc/init.d/openl2tp start")) , KVpncEnum::debug);
                    else
                        GlobalConfig->appendLogEntry(i18n("\"%1\" still running, waiting"  , QString("/etc/init.d/openl2tp stop")) , KVpncEnum::debug);
                }
            }
            currentConnectCounter++;
            usleep(200);
            if (GlobalConfig->appPointer->hasPendingEvents())
                GlobalConfig->appPointer->processEvents();

            if (currentConnectCounter > GlobalConfig->currentProfile->getMaxConnectTries() *1000) {
                if (silent == false) {
                    if (GlobalConfig->KvpncDebugLevel > 2) {
                        if (stop == false) {
                            GlobalConfig->appendLogEntry(i18n("\"%1\" still running but needs too long, stopping"  , QString("/etc/init.d/openl2tp start")) , KVpncEnum::debug);
                        } else {
                            GlobalConfig->appendLogEntry(i18n("\"%1\" still running but needs too long, stopping"  , QString("/etc/init.d/openl2tp stop")) , KVpncEnum::debug);
                        }
                    }
                    if (silent == false || GlobalConfig->KvpncDebugLevel > 8) {
                        disconnect(StartStopOpenl2tpProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_startstopOpenl2tp()));
                        disconnect(StartStopOpenl2tpProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_startstopOpenl2tp()));
                    }

                    disconnectClicked();
                    return;
                }

            }
        }

    }
    delete StartStopOpenl2tpProcess;
    StartStopOpenl2tpProcess = 0L;
}

QString KVpnc::getX509CertificateID(QString Cert, bool user)
{
    issuerID = "";
    userID = "";

    /*
    issuer
    openssl x509 -noout -issuer -in mykeys.pem

    user
    openssl x509 -noout -subject -in mykeys.pem
    */
    putenv((char*)("LC_ALL=C"));
    X509CertificateExtractProcess = new QProcess(this);
    QString proc = GlobalConfig->pathToOpenssl;
    QStringList args;
    args.append("x509");
    args.append("-noout");
    if (user)
        args.append("-subject");
    else
        args.append("-issuer");

    args.append("-in");
    args.append(Cert);

    X509CertificateExtractUser = user;

    connect(X509CertificateExtractProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_getX509CertificateID()));
    connect(X509CertificateExtractProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_getX509CertificateID()));

    X509CertificateExtractProcess->setEnvironment(*env);
    X509CertificateExtractProcess->start(proc, args);
    if (!X509CertificateExtractProcess->waitForStarted()) {
        disconnect(X509CertificateExtractProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_getX509CertificateID()));
        disconnect(X509CertificateExtractProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_getX509CertificateID()));
        delete X509CertificateExtractProcess;
        X509CertificateExtractProcess = 0L;
        KMessageBox::error(this, i18n("Failed to start \"%1\"." , QString("openssl")));
        GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("openssl")) , KVpncEnum::error);
        return "";
    } else {
        //KMessageBox::information( this, i18n( "\"%1\" started." ,"openssl") );
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString("openssl (getCertificate)")), KVpncEnum::debug);
        X509CertificateExtractRunning = true;

        waitForFinished(X509CertificateExtractProcess, 100);

        X509CertificateExtractRunning = false;
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("OpenSSL finished.\n"), KVpncEnum::debug);

        disconnect(X509CertificateExtractProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_getX509CertificateID()));
        disconnect(X509CertificateExtractProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_getX509CertificateID()));
        delete X509CertificateExtractProcess;
        X509CertificateExtractProcess = 0L;
        if (user)
            return userID;
        else
            return issuerID;
    }
}

void KVpnc::readFromStdout_getX509CertificateID()
{
    QStringList msg_list = QString(X509CertificateExtractProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("ID found: %1" , msg.section('=', 1)), KVpncEnum::debug);
        if (X509CertificateExtractUser) {
            userID = msg.section('=', 1);    // subject = /C=DE... => /C=DE...

            while (userID.left(1) == " ")
                userID = userID.right(userID.length() - 1);

        } else {
            issuerID = msg.section('=', 1);    // issuer= /C=DE... => /C=DE...
            while (issuerID.left(1) == " ")
                issuerID = issuerID.right(issuerID.length() - 1);
        }
    }
}

void KVpnc::readFromStderr_getX509CertificateID()
{
    QStringList msg_list = QString(X509CertificateExtractProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("getX509CertificateID() err: %1" , msg), KVpncEnum::debug);
    }
}

void KVpnc::importCertClicked()
{
    ImportCertificateDialog dlg(this, i18n("Import certificate...").toAscii(), GlobalConfig);
    //int result =
    dlg.exec();
}

void KVpnc::manageCiscoCertClicked()
{
    ManageCiscoCert dlg(this, i18n("Manage Cisco certificates...").toAscii(), GlobalConfig);
    //int result =
    dlg.exec();
}

void KVpnc::enrollCiscoCertClicked()
{
    QString ciscoCertMgr = GlobalConfig->pathToCiscoCertMgr;

    if (!ciscoCertMgr.isEmpty() && QFile::exists(ciscoCertMgr)) {
        CiscoCertificateEnrollment dlg(i18n("Enroll certificate..."), GlobalConfig, this);
        dlg.exec();
    } else {
        KMessageBox::error(0,
                           i18n("cisco_cert_mgr is missing.\n"
                                "Please install it and retry."),
                           i18n("Missing tool"));
    }
}

void KVpnc::showProfileManagerClicked()
{
    showProfilesOnly = true;
    slotSettings();
}

void KVpnc::executeCommandBeforeConnect()
{
    if (GlobalConfig->currentProfile->getExecuteCmdBeforeConnect() && !GlobalConfig->currentProfile->getCommandBeforeConnect().isEmpty()) {
        QStringList cmds = GlobalConfig->currentProfile->getCommandBeforeConnect().split('\n', QString::KeepEmptyParts);

        // write command after connect script
        QString CmdBeforeConnectScript = tmpPath + "cmd_before_connect_script." + GlobalConfig->currentProfile->getName();

        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("CmdBeforeConnectScript: " + CmdBeforeConnectScript + "\n", KVpncEnum::debug);
        QFile file(CmdBeforeConnectScript);
        QTextStream stream(&file);
        if (file.open(QIODevice::WriteOnly)) {
            for (QStringList::Iterator it = cmds.begin(); it != cmds.end(); ++it)
                stream << *it << " ; ";
            file.close();

            CmdBeforeConnectProcess = new QProcess(this);
            QString proc = GlobalConfig->InterpreterShell;
            QStringList args;
            args.append(CmdBeforeConnectScript);

            connect(CmdBeforeConnectProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_executeCommandBeforeConnect()));
            connect(CmdBeforeConnectProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_executeCommandBeforeConnect()));

            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Executing command before connect:\n%1"  , QString(cmds.join(";"))), KVpncEnum::debug);
            CmdBeforeConnectProcess->setEnvironment(*env);
            CmdBeforeConnectProcess->start(proc, args);
            if (!CmdBeforeConnectProcess->waitForStarted()) {
                KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , CmdBeforeConnectScript));
                disconnect(CmdBeforeConnectProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_executeCommandBeforeConnect()));
                disconnect(CmdBeforeConnectProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_executeCommandBeforeConnect()));
                delete CmdBeforeConnectProcess;
                CmdBeforeConnectProcess = 0L;
                disconnectClicked();
            } else {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("\"%1\" started."  , QString("CmdBeforeConnectScript")), KVpncEnum::debug);

                waitForFinished(CmdBeforeConnectProcess, 100);

                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("\"%1\" finished." , QString("CmdBeforeConnectScript")), KVpncEnum::debug);
                disconnect(CmdBeforeConnectProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_executeCommandBeforeConnect()));
                disconnect(CmdBeforeConnectProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_executeCommandBeforeConnect()));
                delete CmdBeforeConnectProcess;
                CmdBeforeConnectProcess = 0L;
            }

        } else {
            // file could not written
        }
    }
}

void KVpnc::executeCommandAfterConnect()
{
    if (GlobalConfig->currentProfile->getExecuteCmdAfterConnect() && !GlobalConfig->currentProfile->getCommandAfterConnect().isEmpty()) {
        QStringList cmds = GlobalConfig->currentProfile->getCommandAfterConnect().split('\n', QString::KeepEmptyParts);

        // write command after connect script
        QString CmdAfterConnectScript = tmpPath + "cmd_after_connect_script." + GlobalConfig->currentProfile->getName();
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("CmdAfterConnectScript: " + CmdAfterConnectScript + "\n", KVpncEnum::debug);
        QFile file(CmdAfterConnectScript);
        QTextStream stream(&file);
        if (file.open(QIODevice::WriteOnly)) {
            for (QStringList::Iterator it = cmds.begin(); it != cmds.end(); ++it)
                stream << *it << " ; ";

            file.close();

            CmdAfterConnectedProcess = new QProcess(this);
            QString proc = GlobalConfig->InterpreterShell;
            QStringList args;
            args.append(CmdAfterConnectScript);


            connect(CmdAfterConnectedProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_executeCommandAfterConnect()));
            connect(CmdAfterConnectedProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_executeCommandAfterConnect()));

            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Sleeping %1s before executing command after connect..." , QString().setNum(GlobalConfig->currentProfile->getCommandAfterConnectDelayTime())), KVpncEnum::debug);
            for (int i=0; i<= GlobalConfig->currentProfile->getCommandAfterConnectDelayTime()*1000; i+=100) {
                usleep(100);
            }

            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Executing command after connect:\n%1" , cmds.join("; ")), KVpncEnum::debug);
            CmdAfterConnectedProcess->setEnvironment(*env);
            CmdAfterConnectedProcess->start(proc, args);
            if (!CmdAfterConnectedProcess->waitForStarted()) {
                KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , CmdAfterConnectScript));
                disconnect(CmdAfterConnectedProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_executeCommandAfterConnect()));
                disconnect(CmdAfterConnectedProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_executeCommandAfterConnect()));
                delete CmdAfterConnectedProcess;
                CmdAfterConnectedProcess = 0L;
                disconnectClicked();
            } else {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString("CmdAfterConnectScript")), KVpncEnum::debug);

                waitForFinished(CmdAfterConnectedProcess, 100);

                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("\"%1\" finished." , QString("CmdAfterConnectScript")), KVpncEnum::debug);
                disconnect(CmdAfterConnectedProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_executeCommandAfterConnect()));
                disconnect(CmdAfterConnectedProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_executeCommandAfterConnect()));
                delete CmdAfterConnectedProcess;
                CmdAfterConnectedProcess = 0L;
            }
        } else {
            // file could not written
        }

    }
}

void KVpnc::executeCommandBeforeDisconnect()
{
    if (GlobalConfig->currentProfile->getExecuteCmdBeforeDisconnect() && !GlobalConfig->currentProfile->getCommandBeforeDisconnect().isEmpty()) {
        QStringList cmds = GlobalConfig->currentProfile->getCommandBeforeDisconnect().split('\n', QString::KeepEmptyParts);

        // write command after connect script
        QString CmdBeforeDisconnectScript = tmpPath + "cmd_before_disconnect_script." + GlobalConfig->currentProfile->getName();
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("CmdBeforeDisconnectScript: " + CmdBeforeDisconnectScript + "\n", KVpncEnum::debug);
        QFile file(CmdBeforeDisconnectScript);
        QTextStream stream(&file);
        if (file.open(QIODevice::WriteOnly)) {
            for (QStringList::Iterator it = cmds.begin(); it != cmds.end(); ++it)
                stream << *it << " ; ";
            file.close();

            CmdBeforeDisconnectProcess = new QProcess(this);
            QString proc = GlobalConfig->InterpreterShell;
            QStringList args;
            args.append(CmdBeforeDisconnectScript);

            connect(CmdBeforeDisconnectProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_executeCommandBeforeDisconnect()));
            connect(CmdBeforeDisconnectProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_executeCommandBeforeDisconnect()));

            CmdBeforeDisconnectProcess->setEnvironment(*env);
            CmdBeforeDisconnectProcess->start(proc, args);
            if (!CmdBeforeDisconnectProcess->waitForStarted()) {
                KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , CmdBeforeDisconnectScript));
                disconnect(CmdBeforeDisconnectProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_executeCommandBeforeDisconnect()));
                disconnect(CmdBeforeDisconnectProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_executeCommandBeforeDisconnect()));
                delete CmdBeforeDisconnectProcess;
                CmdBeforeDisconnectProcess = 0L;
                disconnectClicked();
            } else {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString("CmdBeforeDisconnectScript")) , KVpncEnum::debug);

                waitForFinished(CmdBeforeDisconnectProcess, 100);

                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("\"%1\" finished." , QString("CmdBeforeDisconnectScript")), KVpncEnum::debug);
                disconnect(CmdBeforeDisconnectProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_executeCommandBeforeDisconnect()));
                disconnect(CmdBeforeDisconnectProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_executeCommandBeforeDisconnect()));
                delete CmdBeforeDisconnectProcess;
                CmdBeforeDisconnectProcess = 0L;
            }


        } else {
            // file could not written
        }
    }
}

void KVpnc::executeCommandAfterDisconnect()
{
    if (GlobalConfig->currentProfile->getExecuteCmdAfterDisconnect() && !GlobalConfig->currentProfile->getCommandAfterDisconnect().isEmpty()) {
        QStringList cmds = GlobalConfig->currentProfile->getCommandAfterDisconnect().split('\n', QString::KeepEmptyParts);

        // write command after connect script
        QString CmdAfterDisconnectScript = tmpPath + "cmd_after_disconnect_script." + GlobalConfig->currentProfile->getName();

        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("CmdAfterDisconnectScript: " + CmdAfterDisconnectScript + "\n", KVpncEnum::debug);
        QFile file(CmdAfterDisconnectScript);
        QTextStream stream(&file);
        if (file.open(QIODevice::WriteOnly)) {
            for (QStringList::Iterator it = cmds.begin(); it != cmds.end(); ++it)
                stream << *it << " ; ";
            file.close();

            CmdAfterDisconnectedProcess = new QProcess(this);
            QString proc = GlobalConfig->InterpreterShell;
            QStringList args;
            args.append(CmdAfterDisconnectScript);

            connect(CmdAfterDisconnectedProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_executeCommandAfterDisconnect()));
            connect(CmdAfterDisconnectedProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_executeCommandAfterDisconnect()));

            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Executing command after disconnect:\n%1" , cmds.join("; ")), KVpncEnum::debug);

            CmdAfterDisconnectedProcess->setEnvironment(*env);
            CmdAfterDisconnectedProcess->start(proc, args);
            if (!CmdAfterDisconnectedProcess->waitForStarted()) {
                KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , CmdAfterDisconnectScript));
                disconnect(CmdAfterDisconnectedProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_executeCommandAfterDisconnect()));
                disconnect(CmdAfterDisconnectedProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_executeCommandAfterDisconnect()));
                delete CmdAfterDisconnectedProcess;
                CmdAfterDisconnectedProcess = 0L;
                disconnectClicked();
            } else {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString("CmdAfterDisconnectScript")), KVpncEnum::debug);

                waitForFinished(CmdAfterDisconnectedProcess, 100);

                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("\"%1\" finished." , QString("CmdAfterDisconnectScript")), KVpncEnum::debug);
                disconnect(CmdAfterDisconnectedProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_executeCommandAfterDisconnect()));
                disconnect(CmdAfterDisconnectedProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_executeCommandAfterDisconnect()));
                delete CmdAfterDisconnectedProcess;
                CmdAfterDisconnectedProcess = 0L;
            }

        } else {
            // file could not written
        }
    }
}

void KVpnc::setFirewallAfterConnect()
{

    // write firewall after connect script
    QString SetFirewallAfterConnectScript = tmpPath + "firewall_after_connect_script." + GlobalConfig->currentProfile->getName();
    if (GlobalConfig->KvpncDebugLevel > 0)
        GlobalConfig->appendLogEntry("setFirewallAfterConnectScript: " + SetFirewallAfterConnectScript + "\n", KVpncEnum::debug);
    QFile file(SetFirewallAfterConnectScript);
    QTextStream stream(&file);
    if (file.open(QIODevice::WriteOnly)) {
        if (GlobalConfig->currentProfile->getFixPathMtuDiscoveryProblem() && Utils(GlobalConfig).getToolInfo("iptables")->found) {
            //  iptables --append FORWARD --protocol tcp --tcp-flags SYN,RST SYN --jump TCPMSS --clamp-mss-to-pmtu
            // see http://pptpclient.sourceforge.net/howto-diagnosis.phtml#connections_freeze
            if (GlobalConfig->KvpncDebugLevel > 2)
                GlobalConfig->appendLogEntry(i18n("Insert rule for fixing path MTU discovery problem"), KVpncEnum::debug);

            stream << "\n";
            stream << GlobalConfig->pathToIptables << " --append FORWARD --protocol tcp --tcp-flags SYN,RST SYN --jump TCPMSS --clamp-mss-to-pmtu" << "\n";
        }
        file.close();

        QProcess SetFirewallAfterConnectProcess(this);
        QString proc = GlobalConfig->InterpreterShell;
        QStringList args;
        args.append(SetFirewallAfterConnectScript);
        SetFirewallAfterConnectProcess.setEnvironment(*env);
//    if ( GlobalConfig->KvpncDebugLevel > 0 )
//     GlobalConfig->appendLogEntry ( i18n ( "Set firewall after connect:\n%1" , cmd ), KVpncEnum::debug );
        SetFirewallAfterConnectProcess.start(proc, args);
        if (!SetFirewallAfterConnectProcess.waitForStarted()) {
            KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , SetFirewallAfterConnectScript));
//     disconnectClicked();
        } else {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString("SetFirewallAfterConnectScript")), KVpncEnum::debug);
            waitForFinished(&SetFirewallAfterConnectProcess, 100);

            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("\"%1\" finished." , QString("SetFirewallAfterConnectScript")), KVpncEnum::debug);
        }

    } else {
        // file could not written
    }

}

void KVpnc::setFirewallBeforeDisconnect()
{
    // write firewall after connect script
    QString SetFirewallBeforeDisconnect = tmpPath + "firewall_after_connect_script." + GlobalConfig->currentProfile->getName();
    if (GlobalConfig->KvpncDebugLevel > 0)
        GlobalConfig->appendLogEntry("SetFirewallBeforeDisconnect: " + SetFirewallBeforeDisconnect + "\n", KVpncEnum::debug);
    QFile file(SetFirewallBeforeDisconnect);
    QTextStream stream(&file);
    if (file.open(QIODevice::WriteOnly)) {
        // see http://pptpclient.sourceforge.net/howto-diagnosis.phtml#connections_freeze
        if (GlobalConfig->currentProfile->getFixPathMtuDiscoveryProblem() && Utils(GlobalConfig).getToolInfo("iptables")->found) {

            if (GlobalConfig->KvpncDebugLevel > 2)
                GlobalConfig->appendLogEntry(i18n("Remove rule for fixing path MTU discovery problem"), KVpncEnum::debug);

            stream << "\n";
            stream << GlobalConfig->pathToIptables << " --delete FORWARD --protocol tcp --tcp-flags SYN,RST SYN --jump TCPMSS --clamp-mss-to-pmtu" << "\n";
        }
        file.close();

        QProcess SetFirewallBeforeDisconnectProcess(this);
        QString proc = GlobalConfig->InterpreterShell;
        QStringList args;
        args.append(SetFirewallBeforeDisconnect);
        SetFirewallBeforeDisconnectProcess.setEnvironment(*env);


//    if ( GlobalConfig->KvpncDebugLevel > 0 )
//     GlobalConfig->appendLogEntry ( i18n ( "Set firewall before disconnect:\n%1" , cmd ), KVpncEnum::debug );
        SetFirewallBeforeDisconnectProcess.start(proc, args);
        if (!SetFirewallBeforeDisconnectProcess.waitForStarted()) {
            KMessageBox::sorry(this, i18n("Failed to start \"%1\"." , SetFirewallBeforeDisconnect));
//     disconnectClicked();
        } else {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString("setFirewallBeforeDisconnect")), KVpncEnum::debug);
            waitForFinished(&SetFirewallBeforeDisconnectProcess, 100);

            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("\"%1\" finished." , QString("setFirewallBeforeDisconnect")), KVpncEnum::debug);
        }
    } else {
        // file could not written
    }

}

void KVpnc::doRoutePptp()
{
    /*
    route add -net 192.168.1.0/24 eth0
    */
    putenv((char*)("LC_ALL=C"));
    RouteProcess = new QProcess(this);
    QString proc = GlobalConfig->pathToRoute;
    QStringList args;
    args.append("add");
    args.append("-net");
    QString RemoteNetAddr = GlobalConfig->currentProfile->getRemoteNetAddr();
    QString RemoteNetMask = GlobalConfig->currentProfile->getRemoteNetMask();
    QString RemoteNet = RemoteNetAddr + "/" + RemoteNetMask;
    args.append(RemoteNet);
    QString dev;

    if (!GlobalConfig->currentProfile->getNetworkDevice().isEmpty())
        dev = GlobalConfig->currentProfile->getNetworkDevice();
    else
        dev = "ppp0";

    if (GlobalConfig->KvpncDebugLevel > 0) {
        NetworkInterface iface(GlobalConfig, parent);
        QString defaultinterface = iface.getDefaultInterface();
        GlobalConfig->appendLogEntry(i18n("Default interface %1" , defaultinterface), KVpncEnum::debug);
    }

    args.append(dev);
    tmpInterface = dev;

    connect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_pptp()));
    connect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_pptp()));

    RouteProcess->setEnvironment(*env);
    RouteProcess->start(proc, args);
    if (!RouteProcess->waitForStarted()) {
        KMessageBox::error(this, i18n("Failed to start \"%1\"." , QString("route")));
        GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("route")) , KVpncEnum::error);
        disconnect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_pptp()));
        disconnect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_pptp()));
        delete RouteProcess;
        RouteProcess = 0L;
        disconnectClicked();
        return;
    } else {
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry("route: \"route add -net " + RemoteNet + " " + tmpInterface + "\"", KVpncEnum::debug);
        waitForFinished(RouteProcess, 100);
        disconnect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_pptp()));
        disconnect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_pptp()));
        delete RouteProcess;
        RouteProcess = 0L;
    }

}

void KVpnc::slotConnecting()
{
    setGuiStatus(KVpncEnum::connecting);
}

void KVpnc::profileAddedOrDeleted()
{
    if (!GlobalConfig->AccountList->isEmpty()) {
        this->DeleteSessionAction->setEnabled(true);
        //    this->advancedSessionAction->setEnabled(true);
        this->SaveSessionAction->setEnabled(true);
        this->ImportSessionAction->setEnabled(true);

        this->ConnectAction->setEnabled(true);
        mw->buttonConnect->setEnabled(true);

        mw->SessionCombo->clear();
        QuickConnectMenu->clear();
        VpnAccountData *it;
        for (int accountIdx = 0; accountIdx < GlobalConfig->AccountList->size(); ++accountIdx) {
            it = GlobalConfig->AccountList->at(accountIdx);
            QuickConnectMenu->addAction(it->getName());
            mw->SessionCombo->insertItem(accountIdx, it->getName());
        }
        mw->SessionCombo->model()->sort(0);
        //   if ( !GlobalConfig->lastProfile.isEmpty() ) {
        //   mw->SessionCombo->setCurrentItem( 1 );
        if (GlobalConfig->currentProfile != 0)
            sessionToggled(GlobalConfig->currentProfile->getName());
        else
            sessionToggled(GlobalConfig->AccountList->first()->getName());
        //   }

    } else {
        this->DeleteSessionAction->setEnabled(false);
        //    this->advancedSessionAction->setEnabled(false);
        this->SaveSessionAction->setEnabled(false);
        this->ImportSessionAction->setEnabled(true);

        this->ConnectAction->setEnabled(false);
        mw->buttonConnect->setEnabled(false);
    }

}

bool KVpnc::setVirtualIP()
{
    /*
    if (GlobalConfig->currentProfile->getNetworkDevice().isEmpty() || GlobalConfig->currentProfile->getVirtualIP().isEmpty()){
    KMessageBox::error ( this, i18n( "Empty interface or empty virtual IP." ), i18n( "Bad Value" ) );
    return false;
    }
    if (!Utils( GlobalConfig, parent ).isValidNetworkDevice(GlobalConfig->currentProfile->getNetworkDevice())){
        KMessageBox::error(this, i18n("Interface does not exits."), i18n("No Interface"));
        return false;
    }

    setVirtualIPSuccess=true;
    SetVirtualIPProcess = new QProcess(this);
    QString proc = GlobalConfig->pathToIfconfig;
    QStringList args;
    args.append(QString(NetworkDevice+":100"));
    SetVirtualIPProcess->addArgument(GlobalConfig->currentProfile->getVirtualIP());
    connect( SetVirtualIPProcess, SIGNAL( readyReadStandardOutput() ), this, SLOT( readFromStdout_setVirtualIP() ) );
    connect( SetVirtualIPProcess, SIGNAL( readyReadStandardError())() ), this, SLOT( readFromStderr_setVirtualIP() ) );

    SetVirtualIPProcess->setEnvironment(*env);
    SetVirtualIPProcess->start(proc,args);
    if ( !SetVirtualIPProcess->waitForStarted() )
    {
    return false;
    }
    else {
    SetVirtualIPProcess->waitForFinished();
    disconnect( SetVirtualIPProcess, SIGNAL( readyReadStandardOutput() ), this, SLOT( readFromStdout_setVirtualIP() ) );
    disconnect( SetVirtualIPProcess, SIGNAL( readyReadStandardError())() ), this, SLOT( readFromStderr_setVirtualIP() ) );
    delete SetVirtualIPProcess;
    SetVirtualIPProcess=0L;

    return setVirtualIPSuccess;
    }
    */


    return false;
}

void KVpnc::toggleDebugConsole()
{
    if (!GlobalConfig->showDebugConsole) {
        GlobalConfig->showDebugConsole = true;
        DebugconsoleAction ->setChecked(true);
        mw->DebugOutput->show();
        //resize( minimumSizeHint() );
    } else {
        GlobalConfig->showDebugConsole = false;
        DebugconsoleAction ->setChecked(false);
        mw->DebugOutput->hide();
        //   setMinimumSize(0,0);
        //   this->resize( minimumSizeHint() );
    }
}

void KVpnc::addAdditionalNetworkRoutes()
{
    if (GlobalConfig->currentProfile == 0)
        return ;

    if (!GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty()) {
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("Setting additional network routes..."), KVpncEnum::debug);
        QStringList AdditionalNetworkRoutes = GlobalConfig->currentProfile->getAdditionalNetworkRoutes();

        int count = 1;

        QString dev = GlobalConfig->currentProfile->getNetworkDevice();

        NetworkInterface iface(GlobalConfig, parent);
        QString defaultinterface = iface.getDefaultInterface();


        if (dev.isEmpty()) {
            if (defaultinterface.isEmpty())
                dev = "lo";
            else
                dev = defaultinterface;
        }
        if (dev == "default")
            dev = defaultinterface;
        else
            dev = "lo";

        if (GlobalConfig->KvpncDebugLevel > 1)
            GlobalConfig->appendLogEntry(i18n("Default interface: %1" , dev), KVpncEnum::debug);

        QString tmpPath = KStandardDirs::locateLocal("data", "kvpnc/");
        QFile file(tmpPath + "addAdditionalNetworkRoutes." + GlobalConfig->currentProfile->getName() + ".sh");
        QString Route = "";
        QStringList RoutesList;
        QTextStream stream(&file);
        if (file.open(QIODevice::WriteOnly)) {
            stream << "#!" << GlobalConfig->InterpreterShell << "\n";
            for (QStringList::Iterator it = AdditionalNetworkRoutes.begin(); it != AdditionalNetworkRoutes.end(); ++it) {
                Route += "\t" + QString().setNum(count) + ": ";
                count++;
                QString net = (*it).section('#', 0, 0);

                QString Gateway = QString(*it).section('#', 1, 1);
                QString GatewayString = "";
                QString Interface = QString(*it).section('#', 2, 2);
                QString InterfaceString = "";
                bool extended = false;
                Route += net;
                if (!Gateway.isEmpty() && Gateway != "-") {
                    GatewayString += "gateway ";
                    GatewayString += Gateway;
                    Route +=  " " + i18n("over gateway") + " " + Gateway + "\n";
                    extended = true;
                }
                if (!Interface.isEmpty() && Interface != "-") {
                    InterfaceString += Interface;
                    if (Interface != "default")
                        dev = Interface;
                    Route += " " + i18n("over interface") + " " + dev + "\n";
                    extended = true;
                } else {
                    dev=defaultinterface;
                    Route += " " + i18n ( "over interface" ) + " " + dev + "\n";
                }
                RoutesList.append(Route);
                Route = "";

                if (net.indexOf("/32", 0, Qt::CaseInsensitive) > 0)
                    stream << GlobalConfig->pathToRoute << " add " << net << " " << GatewayString << " " << dev << "\n";
                else
                    stream << GlobalConfig->pathToRoute << " add -net " << net << " " << GatewayString << " " << dev << "\n";

            }
            file.close();
            RouteProcess = new QProcess(this);
            QString proc = GlobalConfig->InterpreterShell;
            QStringList args;
            args.append(tmpPath + "addAdditionalNetworkRoutes." + GlobalConfig->currentProfile->getName() + ".sh");
            tmpInterface = dev;

            connect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_route()));
            connect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_route()));

            RouteProcess->setEnvironment(*env);
            RouteProcess->start(proc, args);
            if (!RouteProcess->waitForStarted()) {
                KMessageBox::error(this, i18n("Failed to start \"%1\"." , QString("route (addtitional network routes)")));
                GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("route (addtitional network routes)")) , KVpncEnum::error);
                //disconnectClicked();
                disconnect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_route()));
                disconnect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_route()));
                delete RouteProcess;
                RouteProcess = 0L;
                return;
            } else {
                if (GlobalConfig->KvpncDebugLevel > 1) {
                    GlobalConfig->appendLogEntry(i18n("Adding the following additional network routes:"), KVpncEnum::debug);
                    for (QStringList::Iterator it = RoutesList.begin(); it != RoutesList.end(); ++it)
                        GlobalConfig->appendLogEntry(*it , KVpncEnum::debug);
                }
                waitForFinished(RouteProcess, 100);
                disconnect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_route()));
                disconnect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_route()));
                delete RouteProcess;
                RouteProcess = 0L;
            }

        }
    }
}

void KVpnc::removeAdditionalNetworkRoutes()
{
    if (!GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty()) {
        QStringList AdditionalNetworkRoutes = GlobalConfig->currentProfile->getAdditionalNetworkRoutes();
        QString dev = GlobalConfig->currentProfile->getNetworkDevice();

        NetworkInterface iface(GlobalConfig, parent);
        QString defaultinterface = iface.getDefaultInterface();
        int count = 1;

        if (dev.isEmpty()) {
            if (defaultinterface.isEmpty())
                dev = "lo";
            else
                dev = defaultinterface;
        }
        if (dev == "default")
            dev = defaultinterface;
        else
            dev = "lo";


        if (GlobalConfig->KvpncDebugLevel > 1)
            GlobalConfig->appendLogEntry(i18n("Default interface: %1" , defaultinterface), KVpncEnum::debug);

        QString tmpPath = KStandardDirs::locateLocal("data", "kvpnc/");
        QFile file(tmpPath + "delAdditionalNetworkRoutes." + GlobalConfig->currentProfile->getName() + ".sh");
        QString Route = "";
        QStringList RoutesList;
        QTextStream stream(&file);
        if (file.open(QIODevice::WriteOnly)) {
            stream << "#!" << GlobalConfig->InterpreterShell << "\n";
            for (QStringList::Iterator it = AdditionalNetworkRoutes.begin(); it != AdditionalNetworkRoutes.end(); ++it) {
                Route += "\t" + QString().setNum(count) + ": ";
                count++;

                QString net = (*it).section('#', 0, 0);

                QString Gateway = QString(*it).section('#', 1, 1);
                QString GatewayString = "";
                QString Interface = QString(*it).section('#', 2, 2);
                QString InterfaceString = "";
                bool extended = false;
                Route += net;
                if (!Gateway.isEmpty() && Gateway != "-") {
                    GatewayString += "gw ";
                    GatewayString += Gateway;
                    Route += " " + i18n("over gateway") + " " + Gateway + "\n";
                    extended = true;
                }
                if (!Interface.isEmpty() && Interface != "-") {
                    InterfaceString += Interface;
                    if (Interface != "default")
                        dev = Interface;
                    Route += " " + i18n("over interface") + " " + dev + "\n";
                    extended = true;
                } else {
                    dev=defaultinterface;
                    Route += " " + i18n ( "over interface" ) + " " + dev + "\n";
                }

                RoutesList.append(Route);
                Route = "";

                if (net.indexOf("/32", 0, Qt::CaseInsensitive) > 0)
                    stream << GlobalConfig->pathToRoute << " del " << net << " " << GatewayString << " " << dev << "\n";
                else
                    stream << GlobalConfig->pathToRoute << " del -net " << net << " " << GatewayString << " " << dev << "\n";

            }
            file.close();
            RouteProcess = new QProcess(this);
            QString proc = GlobalConfig->InterpreterShell;
            QStringList args;
            args.append(tmpPath + "delAdditionalNetworkRoutes." + GlobalConfig->currentProfile->getName() + ".sh");
            tmpInterface = dev;

            RouteProcess->setEnvironment(*env);
            RouteProcess->start(proc, args);
            if (!RouteProcess->waitForStarted()) {
                KMessageBox::error(this, i18n("Failed to start \"%1\"." , QString("route (addtitional network routes)")));
                GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("route (addtitional network routes)")) , KVpncEnum::error);
                disconnect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_route()));
                disconnect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_route()));
                delete RouteProcess;
                RouteProcess = 0L;
                //disconnectClicked();
                return;
            } else {
                if (GlobalConfig->KvpncDebugLevel > 1) {
                    GlobalConfig->appendLogEntry(i18n("Removing the following additional network routes:"), KVpncEnum::debug);
                    for (QStringList::Iterator it = RoutesList.begin(); it != RoutesList.end(); ++it)
                        GlobalConfig->appendLogEntry(*it , KVpncEnum::debug);
                }
                waitForFinished(RouteProcess, 100);
                disconnect(RouteProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_route()));
                disconnect(RouteProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_route()));
                delete RouteProcess;
                RouteProcess = 0L;
            }
        }
    }
}

void KVpnc::showLogViewer()
{
    LogViewerDialog dlg(this, parent , GlobalConfig, i18n("Log Viewer"), 150);
    LogViewerAction->setChecked(true);
    dlg.show();
    dlg.exec();
    LogViewerAction->setChecked(false);
}

void KVpnc::doQuickConnect(QAction *actionSelected)
{
    QString itemtext = actionSelected->text(); //.remove("&", Qt::CaseSensitive);       // argh whe have to strip the automatically generated accl :(

    if (GlobalConfig->KvpncDebugLevel > 4)
        GlobalConfig->appendLogEntry(i18n("Quick connect to \"%1\" selected. Current profile: \"%2\"", itemtext, GlobalConfig->currentProfile->getName()), KVpncEnum::info);

    if (GlobalConfig->status == KVpncEnum::connected) {
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("Connect to \"%1\" requested but still connected to \"%2\", current connection will be terminated." , GlobalConfig->currentProfile->getName() , itemtext), KVpncEnum::info);
        disconnectClicked();
    }
    //KMessageBox::information(0,"item",QString("item: "+itemtext));
    if (GlobalConfig->KvpncDebugLevel > 0)
        GlobalConfig->appendLogEntry(i18n("Connect to \"%1\" requested."  , QString(itemtext)), KVpncEnum::debug);

    if (itemtext != GlobalConfig->currentProfile->getName()) {
        if (GlobalConfig->KvpncDebugLevel > 3)
            GlobalConfig->appendLogEntry(i18n("Switching to %1"  , QString(itemtext)), KVpncEnum::debug);
        bool profileInList = false;
        for (int i = 0; i < GlobalConfig->AccountList->count(); i++) {
            if (GlobalConfig->AccountList->at(i) ->getName() == itemtext) {
                profileInList = true;

                sessionToggled(itemtext);
                mw->SessionCombo->setCurrentItem(itemtext);
                GlobalConfig->currentProfile = GlobalConfig->AccountList->at(i);
                connectClicked();
                break;
            }
        }

    } else {
        connectClicked();
    }
}

void KVpnc::saveGuiOptions()
{
//  GlobalConfig->config->setGroup ( "General Options" );
    KConfigGroup config = GlobalConfig->config->group("General Options");
    config.writeEntry(QString("Mainwindow width"), width());
    config.writeEntry(QString("Mainwindow height"), height());
    config.writeEntry(QString("Mainwindow position x"), x());
    config.writeEntry(QString("Mainwindow position y"), y());
    KConfigGroup configgroup = KGlobal::config()->group("ToolBar Settings");
    toolBar("mainToolBar") ->saveSettings(configgroup);
    GlobalConfig->config->sync();
}

void KVpnc::startConnectionStatusCheck()
{
    KStandardDirs * dirs = KGlobal::dirs();
    QString PingCheckScript = QString(dirs->findResource("data", "kvpnc/ping_check.sh"));
    //GlobalConfig->appendLogEntry( QString("PingCheckScript : " +PingCheckScript), KVpncEnum::debug);
    ConnectionStatusCheckProcess = new QProcess(this);
    QString proc = GlobalConfig->InterpreterShell;
    QStringList args;
    args.append(PingCheckScript);
    QString PathToPing = Utils(GlobalConfig).getToolInfo(QString("ping")) ->PathToExec;

    args.append(PathToPing);

    QString pingDevice = "default";
    if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::cisco)
        pingDevice = VpncDevice;
    else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ciscoorig)
        pingDevice = CiscoVpncDevice;
    else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::pptp)
        pingDevice = PppdDevice;
    else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::racoon)
        pingDevice = "default";
    else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::freeswan)
        pingDevice = "ipsec0";
    else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn)
        pingDevice = OpenvpnDevice;
    else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon)
        pingDevice = L2tpPppDevice;
    else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_freeswan)
        pingDevice = L2tpPppDevice;
    else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::vtun)
        pingDevice = "";
    else if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::ssh)
        pingDevice = SshDevice;

    // fallback
    if (pingDevice.isEmpty())
        pingDevice = "default";

    args.append(pingDevice);
    if (GlobalConfig->KvpncDebugLevel > 4)
        GlobalConfig->appendLogEntry(i18n("Use device %1 for connection status check.", pingDevice), KVpncEnum::debug);

    if (GlobalConfig->currentProfile->getDoPingIP()) {
        args.append(GlobalConfig->currentProfile->getPingHostIP());
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("Use user-defined hostname/IP address (%1) for connection status check." , GlobalConfig->currentProfile->getPingHostIP()), KVpncEnum::debug);
    } else {
        args.append(GlobalConfig->currentProfile->getGateway());
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("Use gateway address (%1) for connection status check." , GlobalConfig->currentProfile->getGateway()), KVpncEnum::debug);
    }
    args.append(QString().setNum(GlobalConfig->currentProfile->getConnectionStatusInterval()));
    args.append(QString().setNum(GlobalConfig->currentProfile->getConnectionStatusCheckSuccessCount()));
    args.append(QString().setNum(1));       // verbosity

    connect(ConnectionStatusCheckProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_connectionStatusCheck()));
    connect(ConnectionStatusCheckProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_connectionStatusCheck()));

    ConnectionStatusCheckProcess->setEnvironment(*env);
    ConnectionStatusCheckProcess->start(proc, args);
    if (!ConnectionStatusCheckProcess->waitForStarted()) {
        disconnect(ConnectionStatusCheckProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_connectionStatusCheck()));
        disconnect(ConnectionStatusCheckProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_connectionStatusCheck()));
        delete ConnectionStatusCheckProcess;
        ConnectionStatusCheckProcess = 0L;

        //KMessageBox::sorry( this, i18n( "Failed to start \"%1\"." , "ping_check.sh" ) );
        GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString("ping_check.sh")) , KVpncEnum::error);
    } else {
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString("ping_check.sh")), KVpncEnum::debug);
    }
}

void KVpnc::generateOpenvpnKey()
{
    GenerateOpenvpnKeyDialog dlg(GlobalConfig, this, i18n("Generate Key"));
    dlg.exec();
}

void KVpnc::preserveNetworkEnvironment()
{
    // TODO really needed? What must be also saved?

    if (GlobalConfig->KvpncDebugLevel > 0)
        GlobalConfig->appendLogEntry(i18n("Preserving network environment"), KVpncEnum::debug);

    // resolv.conf
    QFile originalResolvConfFile("/etc/resolv.conf");
    QString originalResolvConfFileContent = "";
    if (originalResolvConfFile.open(QIODevice::ReadOnly)) {
        originalResolvConfFileContent = QString(originalResolvConfFile.readAll());
        originalResolvConfFile.close();
    }

    QFile backupOriginalResolvConfFile("/etc/resolv.conf.before.kvpnc");
    QTextStream stream(&backupOriginalResolvConfFile);
    if (backupOriginalResolvConfFile.open(QIODevice::WriteOnly)) {
        stream << originalResolvConfFileContent;
        backupOriginalResolvConfFile.close();
    }

    // defaultroute
    QString tmpPath = KStandardDirs::locateLocal("data", "kvpnc/");

    QString GetRouteScript = tmpPath + "get_route.sh";

    QString backupOriginalRoute = KStandardDirs::locateLocal("data", "kvpnc/");
    backupOriginalRoute += "route_before_kvpnc";

    QFile file(GetRouteScript);
    stream.setDevice(&file);
    if (file.open(QIODevice::WriteOnly)) {
        stream << "# generated by kvpnc. Do not edit it." << "\n";
        stream << "\n";
        stream << GlobalConfig->pathToIp + " route show > " + backupOriginalRoute + "\n";
        file.close();
    }


    QProcess RouteInfoProcess(this);
    QString proc = GlobalConfig->InterpreterShell;
    QStringList args;
    args.append(GetRouteScript);
    RouteInfoProcess.setEnvironment(*env);
    RouteInfoProcess.start(proc, args);
    if (!RouteInfoProcess.waitForStarted()) {
        GlobalConfig->appendLogEntry(i18n("unable to start proc (%1)." , i18n("script for getting original route info")), KVpncEnum::error);
    } else {
        waitForFinished(&RouteInfoProcess, 100);
    }


}

void KVpnc::restoreNetworkEnvironment()
{
    if (GlobalConfig->KvpncDebugLevel > 0)
        GlobalConfig->appendLogEntry(i18n("Restoring network environment"), KVpncEnum::debug);

    // resolv.conf
    QFile originalResolvConfFile("/etc/resolv.conf.before.kvpnc");
    QString originalResolvConfFileContent = "";
    if (originalResolvConfFile.open(QIODevice::ReadOnly)) {
        originalResolvConfFileContent = QString(originalResolvConfFile.readAll());
        if (originalResolvConfFileContent.length() > 0) {
            originalResolvConfFile.close();
            QFile backupOriginalResolvConfFile("/etc/resolv.conf");
            QTextStream stream(&backupOriginalResolvConfFile);
            if (backupOriginalResolvConfFile.open(QIODevice::WriteOnly)) {
                stream << originalResolvConfFileContent;
                backupOriginalResolvConfFile.close();
                originalResolvConfFile.remove();
            }
        } else {
            GlobalConfig->appendLogEntry(i18n("Warning: %1 has size 0, not restoring it." , QString("/etc/resolv.conf")), KVpncEnum::debug);
        }
    }

    // default route
    // TODO
    QString backupOriginalRoute = KStandardDirs::locateLocal("data", "kvpnc/");
    backupOriginalRoute += "route_before_kvpnc";
    QFile backupOriginalRouteFile(backupOriginalRoute);

    // FIXME make it in GlobalConfig

    if (backupOriginalRouteFile.open(QIODevice::ReadOnly)) {
        QStringList contentlist = QString(backupOriginalRouteFile.readAll()).split("\n");
        for (int i = 0; i < contentlist.size(); ++i) {
            QString line = contentlist.at(i);
            if (line.contains("default via", Qt::CaseInsensitive)) {                  // default via 192.168.0.5 dev eth0
                QString tmpPath = KStandardDirs::locateLocal("data", "kvpnc/");
                QString RestoreDefaultrouteKvpncExitScript = tmpPath + "restore_defaultroute_kvpnc_exit.sh";

                QFile file(RestoreDefaultrouteKvpncExitScript);
                QTextStream stream(&file);
                if (file.open(QIODevice::WriteOnly)) {
                    stream << "# generated by kvpnc. Do not edit it." << "\n";
                    stream << GlobalConfig->pathToRoute + " del default > /dev/null 2>&1\n";
                    stream << GlobalConfig->pathToIp + " route add " + line + "\n"; // ip route add default via 192.168.0.5 dev eth0
                    file.close();
                }

                QProcess RestoreDefaultrouteKvpncExitProcess(this);
                QString proc = GlobalConfig->InterpreterShell;
                QStringList args;
                args.append(RestoreDefaultrouteKvpncExitScript);
                RestoreDefaultrouteKvpncExitProcess.setEnvironment(*env);
                RestoreDefaultrouteKvpncExitProcess.start(proc, args);
                if (!RestoreDefaultrouteKvpncExitProcess.waitForStarted()) {
                    GlobalConfig->appendLogEntry(i18n("Unable to start proc (%1)." , i18n("Script for restoring defaultroute on kvpnc exit.")), KVpncEnum::error);
                } else {
                    waitForFinished(&RestoreDefaultrouteKvpncExitProcess, 100);
                }


                break;
            }
        }
        backupOriginalRouteFile.close();
    }
}

bool KVpnc::backupResolvConf()
{
    bool success = true;
    QString ResolvConfBackupProfile = tmpPath + "resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName();

    if (GlobalConfig->KvpncDebugLevel > 2)
        GlobalConfig->appendLogEntry(i18n("Backup file of %1: %2" , QString("/etc/resolv.conf") , ResolvConfBackupProfile), KVpncEnum::debug);

    QFile ResolvConfBackupProfileFile(ResolvConfBackupProfile + ".sh");
    QTextStream ResolvConfBackupProfileStream(&ResolvConfBackupProfileFile);
    if (ResolvConfBackupProfileFile.open(QIODevice::WriteOnly)) {
        ResolvConfBackupProfileStream << "# generated by kvpnc. Do not edit it." << "\n";
        ResolvConfBackupProfileStream << "\n";
        ResolvConfBackupProfileStream << "cat /etc/resolv.conf > " + ResolvConfBackupProfile + "\n";
        ResolvConfBackupProfileFile.close();
        QProcess ResolvConfBackupProfileProcess(this);
        QString proc = GlobalConfig->InterpreterShell;
        QStringList args;
        args.append(ResolvConfBackupProfile + ".sh");
        ResolvConfBackupProfileProcess.setEnvironment(*env);
        ResolvConfBackupProfileProcess.start(proc, args);
        if (!ResolvConfBackupProfileProcess.waitForStarted()) {
            //     if ( GlobalConfig->KvpncDebugLevel > 0 )
            GlobalConfig->appendLogEntry(i18n("Backup process of %1 could not be started." , QString("/etc/resolv.conf")), KVpncEnum::error);
            success = false;
        } else {
            if (GlobalConfig->KvpncDebugLevel > 2)
                GlobalConfig->appendLogEntry(i18n("%1 backup process started." , QString("/etc/resolv.conf")), KVpncEnum::debug);
            waitForFinished(&ResolvConfBackupProfileProcess, 100);
        }
    }
    return success;
}

bool KVpnc::restoreResolvConf()
{
    bool success = true;
    QString ResolvConfBackupProfile = tmpPath + "resolv.conf.before.kvpnc_" + GlobalConfig->currentProfile->getName();

    if (GlobalConfig->KvpncDebugLevel > 2)
        GlobalConfig->appendLogEntry(i18n("Restore file of %1: %2" , QString("/etc/resolv.conf") , ResolvConfBackupProfile), KVpncEnum::debug);

    QFile ResolvConfRestoreProfileFile(ResolvConfBackupProfile + ".sh");
    QTextStream ResolvConfRestoreProfileStream(&ResolvConfRestoreProfileFile);
    if (ResolvConfRestoreProfileFile.open(QIODevice::WriteOnly)) {
        ResolvConfRestoreProfileStream << "# generated by kvpnc. Do not edit it." << "\n";
        ResolvConfRestoreProfileStream << "\n";
//         ResolvConfRestoreProfileStream << "chmod u+w  /etc/resolv.conf" << "\n";
        ResolvConfRestoreProfileStream << "cat " + ResolvConfBackupProfile + " > /etc/resolv.conf\n";
        ResolvConfRestoreProfileFile.close();
        QProcess ResolvConfRestoreProfileProcess(this);
        QString proc = GlobalConfig->InterpreterShell;
        QStringList args;
        args.append(ResolvConfBackupProfile + ".sh");
        ResolvConfRestoreProfileProcess.setEnvironment(*env);
        ResolvConfRestoreProfileProcess.start(proc, args);
        if (!ResolvConfRestoreProfileProcess.waitForStarted()) {
            //     if ( GlobalConfig->KvpncDebugLevel > 0 )
            GlobalConfig->appendLogEntry(i18n("Restore process of %1 could not be started." , QString("/etc/resolv.conf")), KVpncEnum::error);
            success = false;
        } else {
            if (GlobalConfig->KvpncDebugLevel > 2)
                GlobalConfig->appendLogEntry(i18n("Restore process of %1 started." , QString("/etc/resolv.conf")), KVpncEnum::debug);
            waitForFinished(&ResolvConfRestoreProfileProcess, 100);
        }
    }

    return success;
}

void KVpnc::backupIpsecSystemConfig()
{
    // backup system files

    if (GlobalConfig->KvpncDebugLevel > 0)
        GlobalConfig->appendLogEntry(i18n("Backing up %1"  , QString("ipsec.conf, ipsec.secrets")), KVpncEnum::debug);


    QString IpsecPrefix = "/etc"; // prefix where ipsec.conf and ipsec.secrets
    // ipsec.conf
    QFile originalIpsecConfFile("/etc/ipsec.conf");
    QTextStream stream(&originalIpsecConfFile);
    QString originalIpsecConfFileContent = "";
    if (!originalIpsecConfFile.exists()) {
        originalIpsecConfFile.setFileName("/etc/ipsec.d/ipsec.conf");
        if (originalIpsecConfFile.exists()) {
            IpsecPrefix = "/etc/ipsec.d";
        } else {
            originalIpsecConfFile.setFileName("/etc/ipsec/ipsec.conf");
            if (originalIpsecConfFile.exists()) {
                IpsecPrefix = "/etc/ipsec";
            }
        }
    }
    if (originalIpsecConfFile.exists()) {
        if (originalIpsecConfFile.open(QIODevice::ReadOnly)) {
            originalIpsecConfFileContent = QString(originalIpsecConfFile.readAll());
            originalIpsecConfFile.close();
        }
        stream.setDevice(0);
    }
    QFile backupOriginalIpsecConfFile(IpsecPrefix + "/ipsec.conf.before.kvpnc");
    stream.setDevice(&backupOriginalIpsecConfFile);
    if (backupOriginalIpsecConfFile.open(QIODevice::WriteOnly)) {
        stream << originalIpsecConfFileContent;
        backupOriginalIpsecConfFile.close();
    } else {
        GlobalConfig->appendLogEntry(i18n("%1 could not be opened. Stop." , QString(IpsecPrefix + "/ipsec.conf.before.kvpnc")), KVpncEnum::error);
        setGuiStatus(KVpncEnum::disconnected);
        return;
    }

    stream.setDevice(0);

    if (GlobalConfig->KvpncDebugLevel > 0)
        GlobalConfig->appendLogEntry(i18n("%1 found in %2, assuming %3 as prefix for %4." , QString("ipsec.conf"), IpsecPrefix , IpsecPrefix , IpsecType), KVpncEnum::debug);

    // ipsec.secret
    QFile originalIpsecSecretFile(IpsecPrefix + "/ipsec.secrets");
    stream.setDevice(&originalIpsecSecretFile);
    QString originalIpsecSecretFileContent = "";
    if (originalIpsecSecretFile.open(QIODevice::ReadOnly)) {
        originalIpsecSecretFileContent = QString(originalIpsecSecretFile.readAll());
        originalIpsecSecretFile.close();
    }
    QFile backupOriginalIpsecSecretFile(IpsecPrefix + "/ipsec.secrets.before.kvpnc");
    stream.setDevice(&backupOriginalIpsecSecretFile);
    if (backupOriginalIpsecSecretFile.open(QIODevice::WriteOnly)) {
        stream << originalIpsecSecretFileContent;
        backupOriginalIpsecSecretFile.close();
    } else {
        GlobalConfig->appendLogEntry(i18n("%1 could not be opened. Stop." , QString(IpsecPrefix + "/ipsec.secrets.before.kvpnc")), KVpncEnum::error);
        setGuiStatus(KVpncEnum::disconnected);
        return;
    }
    stream.setDevice(0);
}

void KVpnc::backupDefaultRoute()
{
    OldDefaultroute = tmpPath + "default-route." + GlobalConfig->currentProfile->getName(); // default-route.<id>
    QString OldDefaultrouteFilePath = tmpPath + "backup_default-route." + GlobalConfig->currentProfile->getName() + ".sh"; // default-route.<id>
    QFile BackupDefaultRouteFile(OldDefaultrouteFilePath);    // warning: static
    QTextStream stream2(&BackupDefaultRouteFile);
    if (BackupDefaultRouteFile.open(QIODevice::WriteOnly)) {
        stream2 << " #!" << GlobalConfig->InterpreterShell << "\n";
        stream2 << GlobalConfig->pathToIp << " route show | grep default > " << OldDefaultroute << "\n";
        BackupDefaultRouteFile.close();

        QProcess BackupDefaultRouteProcess(this);
        QString proc = GlobalConfig->InterpreterShell;
        QStringList args;
        args.append(OldDefaultrouteFilePath);
        BackupDefaultRouteProcess.setEnvironment(*env);
        BackupDefaultRouteProcess.start(proc, args);
        if (!BackupDefaultRouteProcess.waitForStarted()) {
            KMessageBox::sorry(this, i18n("Failed to start \"%1\"."  , QString("backup default route process")));
            GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"."  , QString("backup default route process")), KVpncEnum::error);
        } else {
            if (GlobalConfig->KvpncDebugLevel > 1)
                GlobalConfig->appendLogEntry(i18n("\"%1\" started."  , QString("backup default route process")), KVpncEnum::debug);

            waitForFinished(&BackupDefaultRouteProcess, 100);
            if (GlobalConfig->KvpncDebugLevel > 1)
                GlobalConfig->appendLogEntry(i18n("\"%1\" finished."  , QString("backup default route process")), KVpncEnum::debug);
        }

    } else {
        //KMessageBox::error ( this, i18n ( "Default route could not backed up." ) );
        GlobalConfig->appendLogEntry(i18n("Default route could not backed up."), KVpncEnum::error);
    }
}

void KVpnc::showNewProfileWizardClicked()
{
    NewProfileWizard wizard(GlobalConfig, 0);
    if (wizard.exec() == QDialog::Accepted && wizard.newProfileCreated) {

        bool importOK = true;
        if (importOK) {
            VpnAccountData * account = wizard.profileData;
            //    if (account->getUseConnectionStatusCheck())
            //     KMessageBox::information ( this, "Use connection status check: true", "value" );
            //    else
            //     KMessageBox::information ( this, "Use connection status check: false", "value" );

            VpnAccountData * it;
            bool nameOk = false;
            bool ok = false;
            QString newName = wizard.getName();
            while (nameOk == false) {
                for (int accountIdx = 0; accountIdx < GlobalConfig->AccountList->size(); ++accountIdx) {
                    it = GlobalConfig->AccountList->at(accountIdx);
                    if (it->getName() == account->getName()) {
                        //account->setName( QString( account->getName() + "_2" ) );
                        //     KMessageBox::information ( this, i18n( "Profile name exists!\n It will be renamed to \"%1\"." , account->getName() ), i18n( "Name exist, renamed" ) );
                        KMessageBox::error(this, i18n("Profile name exists."), i18n("Name Exists"));
                        QString newName = KInputDialog::getText(i18n("New Name"), i18n("New name for profile:"), QString(account->getName() += "_2"), &ok);
                        if (ok == false) {
                            KMessageBox::information(0, i18n("Import was canceled."));
                            GlobalConfig->appendLogEntry(i18n("Import was canceled."), KVpncEnum::info);
                            slotStatusMsg(i18n("Import was canceled."), ID_FLASH_MSG);
                            return ;
                        } else {
                            it = GlobalConfig->AccountList->first();
                            account->setName(newName);
                            nameOk = true;
                        }

                    }
                    if ( newName.isEmpty() )
                        nameOk=false;
                    else
                        nameOk = true;
                }
                if ( newName.isEmpty() )
                    nameOk=false;
                else
                    nameOk = true;
            }


            GlobalConfig->AccountList->append(account);
            mw->SessionCombo->clear();
            QuickConnectMenu->clear();

            for (int AccountListIdx = 0; AccountListIdx < int(GlobalConfig->AccountList->count()); AccountListIdx++) {
                QuickConnectMenu->addAction(GlobalConfig->AccountList->at(AccountListIdx) ->getName());
                mw->SessionCombo->insertItem(AccountListIdx, GlobalConfig->AccountList->at(AccountListIdx) ->getName());
                if (GlobalConfig->AccountList->at(AccountListIdx) ->getName() == account->getName()) {
                    GlobalConfig->currentProfile = GlobalConfig->AccountList->at(AccountListIdx);
                    if (GlobalConfig->prefDlgOpen && prefDlg)
                    {
                        // called from prefDlg
                        emit newProfileCreated (account->getName());
                    }
                }
            }
            mw->SessionCombo->model()->sort(0);
            mw->SessionCombo->setCurrentItem(account->getName());
            setProfile(account->getName());

            if (!mw->SessionCombo->isEnabled())
                mw->SessionCombo->setEnabled(true);

            this->ConnectAction->setEnabled(true);
            mw->SessionCombo->setCurrentItem(account->getName());
            sessionToggled(account->getName());
            mw->SessionCombo->setCurrentItem(account->getName());

            GlobalConfig->saveOptions();

            mw->SessionCombo->setEnabled(true);
            DeleteSessionAction->setEnabled(true);
            SaveSessionAction->setEnabled(true);
            ImportSessionAction->setEnabled(true);
            ConnectAction->setEnabled(true);
            mw->buttonConnect->setEnabled(true);

            slotStatusMsg(i18n("Profile \"%1\" added." , mw->SessionCombo->currentText()), ID_FLASH_MSG);
            GlobalConfig->appendLogEntry(i18n("Profile \"%1\" added." , mw->SessionCombo->currentText()) , KVpncEnum::info);
            GlobalConfig->saveOptions();
            saveGuiOptions();

            if (wizard.connectaftercreating) {
                if (wizard.daemonavailable) {
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("Connecting to profile \"%1\" after creating it." , mw->SessionCombo->currentText()) , KVpncEnum::debug);
                    connectClicked();
                } else {
                    if (GlobalConfig->KvpncDebugLevel > 0)
                        GlobalConfig->appendLogEntry(i18n("Connecting to profile \"%1\" is requested but daemon is not available, skipping connecting." , mw->SessionCombo->currentText()) , KVpncEnum::debug);
                }
            }
        } else {
            KMessageBox::information(0, i18n("Import was unsuccessful."));
            GlobalConfig->appendLogEntry(i18n("Import was unsuccessful."), KVpncEnum::info);
            slotStatusMsg(i18n("Import was unsuccessful."), ID_FLASH_MSG);
        }
    } else {
        slotStatusMsg(i18n("Creating new profile canceled."), ID_FLASH_MSG);
        GlobalConfig->appendLogEntry(i18n("Creating new profile canceled."), KVpncEnum::info);
    }
}

void KVpnc::exportOpenvpnProfileClicked()
{
    if (!GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::openvpn)
        return ;

    QString filename = KInputDialog::getText(i18n("OpenVPN export"), i18n("Enter filename for export profile %1:" , GlobalConfig->currentProfile->getName()), "", 0, this);
    if (!filename.isEmpty()) {
        // write openvpn.<profile>.conf
        QFile openvpn_file(filename);
        QTextStream openvpn_stream(&openvpn_file);
        if (openvpn_file.open(QIODevice::WriteOnly)) {
            openvpn_stream << "# generated by kvpnc" << "\n";
            openvpn_stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
            openvpn_stream << "# verbosity" << "\n";
            openvpn_stream << "verb " << GlobalConfig->OpenvpnDebugLevel << "\n\n";

            QString certPath = "/etc/openvpn";
            if (!GlobalConfig->currentProfile->getCertPath().isEmpty())
                certPath = GlobalConfig->currentProfile->getCertPath();

            openvpn_stream << "# change to prefix" << "\n";
            openvpn_stream << "cd " << certPath << "\n";

            if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tun") {
                openvpn_stream << "# use tun device" << "\n";
                openvpn_stream << "dev tun" << "\n\n";
            } else {
                openvpn_stream << "# use tap device" << "\n";
                openvpn_stream << "dev tap" << "\n\n";
            }

            // client mode
            openvpn_stream << "# do not listen" << "\n";
            openvpn_stream << "nobind" << "\n\n";

            if (GlobalConfig->currentProfile->getDisableLzoCompression() == false) {
                openvpn_stream << "# compression" << "\n";
                openvpn_stream << "comp-lzo" << "\n\n";
            }
            openvpn_stream << "" << "\n";

            openvpn_stream << "# try to resolve names infinite" << "\n";
            openvpn_stream << "resolv-retry infinite" << "\n\n";

            // TODO make it dynamiclly
            openvpn_stream << "" << "\n";
            if (GlobalConfig->currentProfile->getAuthType() ==  VpnAccountData::cert) {
                openvpn_stream << "# client cert" << "\n";
                openvpn_stream << "cert " << GlobalConfig->currentProfile->getX509Certificate() << "\n\n";
                openvpn_stream << "" << "\n";
                openvpn_stream << "# client private key" << "\n";
                if (!GlobalConfig->currentProfile->getPskIsInFile())
                    openvpn_stream << "key " << GlobalConfig->currentProfile->getPrivateKey() << "\n\n";
                else
                    openvpn_stream << "key " << GlobalConfig->currentProfile->getPrivateKey() << "\n\n";
                openvpn_stream << "" << "\n";
                openvpn_stream << "# ca" << "\n";
                openvpn_stream << "ca " << GlobalConfig->currentProfile->getCaCertificate() << "\n\n";

                openvpn_stream << "# client side" << "\n";
                openvpn_stream << "tls-client" << "\n\n";
                openvpn_stream << "pull" << "\n\n";
                openvpn_stream << "# diffie hellman parameters" << "\n";
                openvpn_stream << "dh dh1024.pem" << "\n\n";

            } else if (GlobalConfig->currentProfile->getAuthType() ==  VpnAccountData::psk) {
                openvpn_stream << "# client psk" << "\n";
                if (GlobalConfig->currentProfile->getPskIsInFile()) {
                    openvpn_stream << "secret " << GlobalConfig->currentProfile->getPreSharedKeyFile() << "\n\n";
                } else {
                    // write openvpn.<profile>.secret
                    QFile openvpn_secretfile(tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".secret");
                    QTextStream openvpn_secretstream(&openvpn_secretfile);
                    if (openvpn_secretfile.open(QIODevice::WriteOnly)) {
                        openvpn_secretstream << "# generated by kvpnc. Do not edit it." << "\n";
                        openvpn_secretstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
                        openvpn_secretstream << GlobalConfig->currentProfile->getPreSharedKey() << "\n\n";
                    }
                    openvpn_secretfile.close();
                    openvpn_stream << "secret " << tmpPath + "openvpn." + GlobalConfig->currentProfile->getName() + ".secret" << "\n\n";
                }
            }

            if (GlobalConfig->currentProfile->getUseUdp()) {
                openvpn_stream << "\n";
                openvpn_stream << "# use udp" << "\n";
                openvpn_stream << "proto udp" << "\n\n";

                if (GlobalConfig->currentProfile->getUseMssfix()) {
                    openvpn_stream << "\n";
                    openvpn_stream << "# userdefined packet size" << "\n";
                    openvpn_stream << "mssfix " << GlobalConfig->currentProfile->getMssfix() << "\n\n";
                }

                if (GlobalConfig->currentProfile->getUseFragment()) {
                    openvpn_stream << "\n";
                    openvpn_stream << "# userdefined packet size for fragmentation" << "\n";
                    openvpn_stream << "fragment " << GlobalConfig->currentProfile->getFragment() << "\n\n";
                }
            } else {
                openvpn_stream << "" << "\n";
                openvpn_stream << "# use tcp" << "\n";
                openvpn_stream << "proto tcp-client" << "\n\n";
            }
            openvpn_stream << "" << "\n";
            openvpn_stream << "# remote side" << "\n";
            openvpn_stream << "remote " << GlobalConfig->currentProfile->getGateway() << "\n";
            if (GlobalConfig->currentProfile->getUseRemotePort()) {
                openvpn_stream << "\n" << "# port" << "\n" << GlobalConfig->currentProfile->getRemotePort();
            }
            openvpn_stream << "\n\n";

            if (GlobalConfig->currentProfile->getUseVirtualIP()) {
                openvpn_stream << "" << "\n";
                openvpn_stream << "# virtual ip addresses" << "\n";
                openvpn_stream << GlobalConfig->pathToIfconfig << " " << GlobalConfig->currentProfile->getLocalVirtualIP() << GlobalConfig->currentProfile->getRemoteVirtualIP() << "\n\n";


                QString RemoteNetAddr = GlobalConfig->currentProfile->getRemoteNetAddr();
                int RemoteNetMaskNum = GlobalConfig->currentProfile->getRemoteNetMask().toInt();
                QString RemoteNetMask = "255.255.255.0";
                if (RemoteNetMaskNum == 24)
                    RemoteNetMask = "255.255.255.0";
                else if (RemoteNetMaskNum == 25)
                    RemoteNetMask = "255.255.255.128";
                else if (RemoteNetMaskNum == 26)
                    RemoteNetMask = "255.255.255.192";
                else if (RemoteNetMaskNum == 27)
                    RemoteNetMask = "255.255.255.224";
                else if (RemoteNetMaskNum == 28)
                    RemoteNetMask = "255.255.255.240";
                else if (RemoteNetMaskNum == 29)
                    RemoteNetMask = "255.255.255.248";
                else if (RemoteNetMaskNum == 30)
                    RemoteNetMask = "255.255.255.252";
                else if (RemoteNetMaskNum == 31)
                    RemoteNetMask = "255.255.255.254";
                else if (RemoteNetMaskNum == 32)
                    RemoteNetMask = "255.255.255.255";

                openvpn_stream << "" << "\n";
                openvpn_stream << "# route to remote network" << "\n";
                openvpn_stream << "route " << RemoteNetAddr << " " << RemoteNetMask << "\n";
            }
            //openvpn_stream << "" << "\n";
            //openvpn_stream << "# permissions" << "\n";
            //      openvpn_stream << "user nobody" << "\n";
            //      openvpn_stream << "group nogroup" << "\n";

            openvpn_stream << "" << "\n";
            openvpn_stream << "# port" << "\n";
            if (GlobalConfig->currentProfile->getUseUserdefinedPort())
                openvpn_stream << "port " << GlobalConfig->currentProfile->getUserdefinedPort() << "\n\n";
            else
                openvpn_stream << "port 1194" << "\n";

            openvpn_stream << "" << "\n";
            openvpn_stream << "# don't re-read key files across SIGUSR1 or --ping-restart" << "\n";
            openvpn_stream << "persist-key" << "\n\n";

            openvpn_stream << "" << "\n";
            openvpn_stream << "# don't close and reopen TUN/TAP device across SIGUSR1 or --ping-restart restarts" << "\n";
            openvpn_stream << "persist-tun" << "\n\n";

            if (GlobalConfig->currentProfile->getUseNsCertType()) {
                openvpn_stream << "" << "\n";
                if (GlobalConfig->currentProfile->getNsCertType() == "client") {
                    openvpn_stream << "# Require that peer certificate was signed with an explicit nsCertType designation of \"client\"" << "\n";
                    openvpn_stream << "ns-cert-type client" << "\n\n";
                } else {
                    openvpn_stream << "# Require that peer certificate was signed with an explicit nsCertType designation of \"server\"" << "\n";
                    openvpn_stream << "ns-cert-type server" << "\n\n";
                }
            }

            openvpn_stream << "# disable ping restart\n";
            openvpn_stream << "ping-restart 0\n";



            //      openvpn_stream << "# keep the connection alive" << "\n";

            //      // TODO make it dynamiclly
            //      openvpn_stream << "keepalive 10 60" << "\n\n";

            //       openvpn_stream << "# keepalive\n";
            // //       openvpn_stream << "keepalive 10000\n";


            //      openvpn_stream << "# What happen if auth fails\n";
            //      // TODO made option for other types
            //      openvpn_stream << "auth-retry none\n\n";

            // FIXME: can user auth only used in cert mode?
            if (GlobalConfig->currentProfile->getAuthWithUsernameAndPassword()) {
                openvpn_stream << "# we want to authenticate with username and password\n";
                openvpn_stream << "auth-user-pass\n\n";
            }

            if (GlobalConfig->currentProfile->getUseUserdefiniedCipher()) {
                openvpn_stream << "# Use a userdefined cipher\n";
                openvpn_stream << "cipher " << GlobalConfig->currentProfile->getUserdefiniedCipher() << "\n\n";
            }

            if (GlobalConfig->currentProfile->getUseRedirectGateway()) {
                openvpn_stream << "# Automatically execute routing commands to cause all outgoing IP traffic to be redirected over the VPN\n";
                openvpn_stream << "redirect-gateway\n\n";
            }

            if (GlobalConfig->currentProfile->getUseTlsAuth() && !GlobalConfig->currentProfile->getTlsAuthFile().isEmpty()) {
                openvpn_stream << "# Add an additional layer of HMAC authentication on top of the TLS control channel to protect against DoS attacks\n";
                QString direction = "";
                if (GlobalConfig->currentProfile->getAuthenticationDirection() != "none")
                    direction = GlobalConfig->currentProfile->getAuthenticationDirection();
                openvpn_stream << "tls-auth " << GlobalConfig->currentProfile->getTlsAuthFile() << " " << direction << "\n\n";

                if (GlobalConfig->currentProfile->getUseTlsRemoteHost()) {
                    openvpn_stream << "# Accept connections only from a host with X509 name or common name equal to host\n";
                    openvpn_stream << "tls-remote " << GlobalConfig->currentProfile->getTlsRemoteHost() << "\n\n";
                }

                if (GlobalConfig->currentProfile->getUseTlsRemoteHost() && GlobalConfig->currentProfile->getUseTlsAuth())
                    openvpn_stream << "tls-client" << "\n\n";

            }

            if (GlobalConfig->currentProfile->getUseHttpProxy()) {
                openvpn_stream << "# Use a HTTP proxy\n";
                openvpn_stream << "http-proxy " << GlobalConfig->currentProfile->getHttpProxy() << " " << GlobalConfig->currentProfile->getHttpProxyPort() << "\n";
                openvpn_stream << "http-proxy-timeout " << GlobalConfig->currentProfile->getHttpProxyTimeout() << "\n\n";
            }

            openvpn_stream << "up " << tmpPath << "openvpn." << GlobalConfig->currentProfile->getName() << ".up" << "\n";
            openvpn_stream << "down " << tmpPath + "openvpn." << GlobalConfig->currentProfile->getName() << ".down" << "\n";
        }
        openvpn_file.close();
        KMessageBox::information(0, i18n("Export of profile %1 was successful." , GlobalConfig->currentProfile->getName()), i18n("Export successful"));
    }
}

void KVpnc::pptpProcessExited(int, QProcess::ExitStatus)
{
//  GlobalConfig->appendLogEntry ( i18n ( "Connection has been terminated." ), KVpncEnum::info );
//  disconnectClicked();

//  if (QFile("/sbin/resolvconf").exists() && QFile("/etc/init.d/resolvconf").exists())
//  {
//
//    QFile downfile ( tmpPath + "pptpd." + GlobalConfig->currentProfile->getName() + ".down" );
//    QTextStream downstream ( &downfile );
//    if ( downfile.open ( QIODevice::WriteOnly ) )
//    {
//     downstream <<  "#!"<< GlobalConfig->InterpreterShell << "\n";
//     downstream << "# generated by kvpnc. Do not edit it." << "\n";
//     downstream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n\n";
//
//     if (QFile("/sbin/resolvconf").exists() && QFile("/etc/init.d/resolvconf").exists())
//      downstream << "/etc/init.d/resolvconf start\n";
//     downfile.close();
//
//    QProcess pppdDownProcess(this );
//    QString proc = GlobalConfig->InterpreterShell;
//    QStringList args;
//    args.append ( tmpPath + "pptpd." + GlobalConfig->currentProfile->getName() + ".down" );
//    pppdDownProcess.setEnvironment(*env);
//    pppdDownProcess.start(proc,args);
//    if ( !pppdDownProcess->waitForStarted() )
//    {
//     KMessageBox::sorry ( this, i18n ( "Failed to start \"%1\"." , "PptpdDownScript" ) );
//    }
//    else
//    {
//      pppdDownProcess.waitForFinished();
//    }
//   }
//  }
}

void KVpnc::openvpn_exited(int, QProcess::ExitStatus)
{
    disconnect ( OpenvpnProcess, SIGNAL ( processExited() ), this, SLOT ( openvpn_exited() ) );
}

void KVpnc::vtun_exited(int, QProcess::ExitStatus)
{
//  GlobalConfig->appendLogEntry(i18n("%1 has been exited.","vtund"),KVpncEnum::error);
//  sleep(2);
//  if (GlobalConfig->status == KVpncEnum::connecting || KVpncEnum::connected)
//   disconnectClicked();
}

void KVpnc::sshExited(int, QProcess::ExitStatus)
{

}

void KVpnc::ipsecwhack_exited(int, QProcess::ExitStatus)
{
    disconnect(IpsecWhackProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_ipsecwhack()));
    disconnect(IpsecWhackProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_ipsecwhack()));
    delete IpsecWhackProcess;
}

void KVpnc::IpsecWhackStatusProcessExited(int, QProcess::ExitStatus)
{
//  disconnect ( IpsecWhackStatusProcess, SIGNAL ( readAllStandardOutput() ), this, SLOT ( readFromStdout_ipsecwhackstatus() ) );
//  disconnect ( IpsecWhackStatusProcess, SIGNAL ( readyReadStandardError() ), this, SLOT ( readFromStderr_ipsecwhackstatus() ) );
//  disconnect ( IpsecWhackStatusProcess, SIGNAL ( finished(int, QProcess::ExitStatus) ), this, SLOT ( IpsecWhackStatusProcessExited(int, QProcess::ExitStatus) ) );
//  delete(IpsecWhackStatusProcess);
//  IpsecWhackStatusProcess=0;
}

void KVpnc::racoonctlExited(int, QProcess::ExitStatus)
{
    //     disconnect( RacoonctlProcess, SIGNAL( readyReadStandardOutput() ), this, SLOT( readFromStdout_racoonctl() ) );
    //     disconnect( RacoonctlProcess, SIGNAL( readyReadStandardError() ), this, SLOT( readFromStderr_racoonctl() ) );
//     disconnect ( RacoonctlProcess, SIGNAL ( finished ( int, QProcess::ExitStatus )), this, SLOT(racoonctlExited(int, QProcess::ExitStatus)) );
}

void KVpnc::prepareL2tpd(bool do_auth)
{

    if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd) {
        // bug in openswan: only 80 chars in line allowed!!!
        int pppdoptionsfilepathlen = QString("pppoptfile = " + tmpPath + "options." + GlobalConfig->currentProfile->getName() + ".l2tpd").length();
        if (pppdoptionsfilepathlen > 80) {
            KMessageBox::error(this,     i18n("The line length for pppoptfile, %1, is longer than 80 chars. Openswan has an bug and cannot handle that. Please rename the profile to a shorter name." , QString().setNum(pppdoptionsfilepathlen)));
            GlobalConfig->appendLogEntry(i18n("The line length for pppoptfile, %1, is longer than 80 chars. Openswan has an bug and cannot handle that. Please rename the profile to a shorter name." , QString().setNum(pppdoptionsfilepathlen)), KVpncEnum::error);
            stopContinue = true;
            return;
        }

        NetworkInterface iface(GlobalConfig, parent);
        if (GlobalConfig->currentProfile->getNetworkDevice() == "default" || GlobalConfig->currentProfile->getNetworkDevice() == "") {
            tmpInterface = iface.getDefaultInterface();
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Default interface: \"%1\"." , QString((tmpInterface))) , KVpncEnum::debug);
            LocalIP = iface.getInterfaceIP(iface.getDefaultInterface());
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("IP address of default interface: \"%1\"."  , QString(LocalIP)) , KVpncEnum::debug);
        } else {
            tmpInterface = GlobalConfig->currentProfile->getNetworkDevice();
            LocalIP = iface.getInterfaceIP(GlobalConfig->currentProfile->getNetworkDevice());
        }

        // write l2tpd.conf
        QFile L2tpdConfigFile(tmpPath + "l2tpd." + GlobalConfig->currentProfile->getName() + ".conf");
        QTextStream stream(&L2tpdConfigFile);
        if (L2tpdConfigFile.open(QIODevice::WriteOnly)) {
            stream << "[global]" << "\n";

            //   if ( !LocalIP.isEmpty() )
            stream << "listen-addr = " << LocalIP << "\n";
            //   else
            //    stream << "listen-addr = 127.0.0.1" <<"\n";
            //   stream << "listen-addr = 0.0.0.0" <<"\n";

            stream << "port = 1701" << "\n";
            if (do_auth) {
                stream << "auth file = /etc/l2tpd/l2tp-secrets" << "\n";
            }


            if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists()) {
                if (GlobalConfig->enableDebugXl2tpdNetwork)
                    stream << "debug network = yes" << "\n";
                if (GlobalConfig->enableDebugXl2tpdpacket)
                    stream << "debug packet = yes" << "\n";
                if (GlobalConfig->enableDebugXl2tpdstate)
                    stream << "debug state = yes" << "\n";
                if (GlobalConfig->enableDebugXl2tpdtunnel)
                    stream << "debug tunnel = yes" << "\n";
            }


            stream << "[lac " << GlobalConfig->currentProfile->getName() << "]" << "\n";
            stream << "lns = " << GlobalConfig->currentProfile->getGateway() << "\n";
            stream << "redial = yes" << "\n";
            stream << "redial timeout = 20" << "\n";
            stream << "max redials = 15" << "\n";
            //     stream << "hidden bit = yes" << "\n";
            stream << "length bit = yes" << "\n";

            // do not need to let authenticate the peer
            if (do_auth)
            {
                stream << "require authentication = yes" << "\n";
            }
            else
            {
                stream << "require authentication = no" << "\n";
            }

            if (GlobalConfig->currentProfile->getAuthMethod() == "chap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2") {
                stream << "require chap = yes" << "\n";
                stream << "refuse pap = yes" << "\n";
            }
            if (GlobalConfig->currentProfile->getAuthMethod() == "pap") {
                stream << "refuse chap = yes" << "\n";
                stream << "require pap = yes" << "\n";
            }

            QString UsernameStr = "";
            if (!GlobalConfig->currentProfile->getUserName().isEmpty())
                UsernameStr = GlobalConfig->currentProfile->getUserName();

            if (UsernameStr.isEmpty() && !GlobalConfig->TmpUsername.isEmpty())
                UsernameStr = GlobalConfig->TmpUsername;

            if (GlobalConfig->KvpncDebugLevel > 1)
                GlobalConfig->appendLogEntry(i18n("Username: %1" , UsernameStr), KVpncEnum::debug);



            stream << "name = " << UsernameStr << "\n";
            stream << "pppoptfile = " << tmpPath + "options." + GlobalConfig->currentProfile->getName() + ".l2tpd" << "\n";
            stream << "ppp debug = yes" << "\n";
            stream << "autodial = yes" << "\n";
            L2tpdConfigFile.close();

            L2tpdProcess = 0L;
        } else {
            GlobalConfig->appendLogEntry(i18n("Creating %1 failed." , QString("l2tpd config file")), KVpncEnum::error);
            stopContinue = true;
        }


        // write options.l2tpd
        QFile L2tpdPppdOptionsFile(tmpPath + "options." + GlobalConfig->currentProfile->getName() + ".l2tpd");
        stream.setDevice(&L2tpdPppdOptionsFile);
        if (L2tpdPppdOptionsFile.open(QIODevice::WriteOnly)) {
            stream << "noauth" << "\n";
            stream << "user " << GlobalConfig->currentProfile->getUserName() << "\n";
            stream << "ipcp-accept-local" << "\n";
            stream << "ipcp-accept-remote" << "\n";
            //     stream << "crtscts" << "\n";
            stream << "idle 180" << "\n";
            stream << "lock" << "\n";
            //     stream << "proxyarp" << "\n";
            //     stream << "connect-delay 5000" << "\n";
            //     stream << "persist" << "\n";
            //     stream << "hide-password" << "\n";
            //     if (!GlobalConfig->currentProfile->getUseDnsServer())
            //      stream << "usepeerdns" << "\n";
            //     stream << "asyncmap 0" << "\n";
            //     stream << "crtscts" << "\n";
            //     stream << "lock" << "\n";
            //     stream << "lcp-echo-interval 10" << "\n";
            //     stream << "lcp-echo-failure 3" << "\n";
            //     stream << "noipx" << "\n";

            stream << "linkname kvpnc." << GlobalConfig->currentProfile->getName() << "\n";
            // FIXME how i can get safe the right interface name otherway?


            if (GlobalConfig->PppdDebugLevel)
                stream << "debug" << "\n";
            //stream << "kdebug 1" << "\n";

            if (!pppdCapabilitiesCollected) {
                GlobalConfig->appPointer->setOverrideCursor(QCursor(Qt::WaitCursor));
                if (GlobalConfig->KvpncDebugLevel > 3)
                    GlobalConfig->appendLogEntry(i18n("Collecting pppd capabilities..."), KVpncEnum::debug);
                GlobalConfig->pppdcap = Utils(GlobalConfig).checkPppdCapabilities();
                pppdCapabilitiesCollected = true;
                GlobalConfig->appPointer->restoreOverrideCursor();
            }
            pppdHasReplacedefaultrouteSupport = GlobalConfig->pppdcap.pppdHasReplacedefaultrouteSupport;


            if (GlobalConfig->currentProfile->getAuthMethod() == "chap") {
                stream << "# use chap" << "\n";
                stream << GlobalConfig->pppdcap.RequireAuthChapOption << "\n";
            }

            if (GlobalConfig->currentProfile->getAuthMethod() == "mschap") {
                stream << "# use mschap" << "\n";
                stream << GlobalConfig->pppdcap.RequireAuthMschapOption << "\n";
            }

            if (GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2") {
                stream << "# use mschap-v2" << "\n";
                stream << GlobalConfig->pppdcap.RequireAuthMschapv2Option << "\n";
            }

            if (GlobalConfig->currentProfile->getAuthMethod() == "pap") {
                stream << "# use pap" << "\n";
                stream << GlobalConfig->pppdcap.RequireAuthPapOption << "\n";
            }

            if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists()) {
                if (GlobalConfig->enableDebugPppd)
                    stream << "debug" << "\n";
            } else {
                if (GlobalConfig->enableDebugPppd)
                    stream << "debug" << "\n";
            }

            if (!GlobalConfig->currentProfile->getReplaceDefaultRoute()) {
                stream << "# do not set defaultroute\n";
                stream << "nodefaultroute";
                stream << "\n";
            } else {
                if (GlobalConfig->currentProfile->getReplaceDefaultRoute()) {
                    stream << "# set defaultroute\n";
                    stream << "defaultroute\n";
                    if (GlobalConfig->pppdcap.pppdHasReplacedefaultrouteSupport)
                        stream << "replacedefaultroute\n";
                }
                stream << "\n";
            }

            if (GlobalConfig->currentProfile->getUseMtu()) {
                stream << "mtu " << GlobalConfig->currentProfile->getMtu() << "\n";
            }
            if (GlobalConfig->currentProfile->getUseMru()) {

                stream << "mru " << GlobalConfig->currentProfile->getMru() << "\n";
            }

            stream << "connect-delay 5000" << "\n";



            L2tpdPppdOptionsFile.close();
        } else {
            GlobalConfig->appendLogEntry(i18n("Creating %1 failed." , i18n("l2tpd options file for pppd")), KVpncEnum::error);
            stopContinue = true;
        }

//  // write l2tp secrets file
//  QString L2tpSecrets = tmpPath + "l2tp-secrets." + GlobalConfig->currentProfile->getName();
//
//  if ( GlobalConfig->KvpncDebugLevel > 0 )
//   GlobalConfig->appendLogEntry ( i18n ( "l2tp secrets file: %1" , tmpPath + "l2tp-secrets." + GlobalConfig->currentProfile->getName() ), KVpncEnum::debug );
//  QFile L2tpdSecretsFile ( L2tpSecrets );
//  stream.setDevice ( &L2tpdSecretsFile );
//  if ( L2tpdSecretsFile.open ( QIODevice::WriteOnly | IO_WriteOnly ) )
//  {
//   stream << "# +++ generated by kvpnc. Do not edit it." << "\n";
//   stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";
//
//   if ( GlobalConfig->currentProfile->getSaveUserPassword() )
//    GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserPassword();
//
//   QString UsernameStr;
//   if ( !GlobalConfig->currentProfile->getDontSaveUsername() )
//    UsernameStr = GlobalConfig->currentProfile->getUserName();
//   else
//    UsernameStr = GlobalConfig->TmpUsername;
//
//   if (GlobalConfig->TmpUsername.isEmpty() && !GlobalConfig->currentProfile->getUserName().isEmpty() )
//    GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();
//
//
//   if (GlobalConfig->KvpncDebugLevel > 1)
//    GlobalConfig->appendLogEntry ( i18n ( "Username: %1" , GlobalConfig->TmpUsername.isEmpty() ), KVpncEnum::debug );
//
//   stream << "* " << GlobalConfig->currentProfile->getGateway() + " \"" << GlobalConfig->TmpPassword << "\" *\n";
//   stream << GlobalConfig->currentProfile->getGateway() << " \"" << GlobalConfig->TmpPassword << "\" *\n";
//
//   stream << "# --- generated by kvpnc. Do not edit it." << "\n";
//   L2tpdSecretsFile.close();
//   Utils ( GlobalConfig, this ).doChmod ( L2tpdSecretsFile.name(), "go-rwx" );
//
//  }
//  else
//  {
//   GlobalConfig->appendLogEntry ( i18n ( "Creating of %1 failed." , "l2tpd secrets file" ), KVpncEnum::error );
//   stopContinue = true;
//  }

        if (GlobalConfig->currentProfile->getAuthMethod() == "chap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap" || GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2") {

            Utils(GlobalConfig, this).doChmod("/etc/ppp/pap-secrets", "go-rwx");

            // write pppd /etc/ppp/chap-secrets
            QString ChapSecrets = "/etc/ppp/chap-secrets"; // /etc/ppp/chap-secrets

            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1", QString("/etc/ppp/chap-secrets")), KVpncEnum::debug);
            QFile ChapSecretsFile(ChapSecrets);
            stream.setDevice(&ChapSecretsFile);
            if (ChapSecretsFile.open(QIODevice::WriteOnly | QIODevice::Append)) {
                stream << "# +++ generated by kvpnc. Do not edit it." << "\n";
                stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";

                if (GlobalConfig->currentProfile->getSaveUserPassword())
                    GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserPassword();

                QString UsernameStr;
                if (!GlobalConfig->currentProfile->getDontSaveUsername())
                    UsernameStr = GlobalConfig->currentProfile->getUserName();
                else
                    UsernameStr = GlobalConfig->TmpUsername;

                GlobalConfig->appendLogEntry(i18n("Username: %1" , UsernameStr), KVpncEnum::debug);

                if (GlobalConfig->currentProfile->getUseNtDomainName() && !GlobalConfig->currentProfile->getNtDomainName().isEmpty()) {
                    // line: "<domainname>\\<username>"<tab><remote host><tab>"<password>"<tab><ip address>
                    stream << "\"" << GlobalConfig->currentProfile->getNtDomainName() << "\\\\" << UsernameStr << "\"\t" << "*" << "\t" << " \"" << GlobalConfig->TmpPassword << "\"\t*\n";
                } else {
                    // line: "<username>"<tab><remote host><tab>"<password>"<tab><ip address>
                    stream << "\"" << UsernameStr << "\"\t" << "*" << "\t" << " \"" << GlobalConfig->TmpPassword << "\"\t*\n";

                }
                stream << "# --- generated by kvpnc. Do not edit it." << "\n";
                ChapSecretsFile.close();


                Utils(GlobalConfig, this).doChmod("/etc/ppp/chap-secrets", "go-rwx");
            }
        }
        if (GlobalConfig->currentProfile->getAuthMethod() == "pap") {

            //GlobalConfig->appendLogEntry ( i18n ( "Creating of %1 failed." , "pppd secrets file" ), KVpncEnum::error );
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Authentication method: %1" , GlobalConfig->currentProfile->getAuthMethod()), KVpncEnum::debug);


            Utils(GlobalConfig, this).doChmod("/etc/ppp/chap-secrets", "go-rwx");

            // write pppd /etc/ppp/pap-secrets
            QString papSecrets = "/etc/ppp/pap-secrets"; // /etc/ppp/pap-secrets
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("pppd secrets file: %1" , QString("/etc/ppp/pap-secrets")), KVpncEnum::debug);
            QFile papSecretsFile(papSecrets);
            papSecretsFile.setFileName(papSecrets);
            stream.setDevice(&papSecretsFile);
            if (papSecretsFile.open(QIODevice::WriteOnly | QIODevice::Append)) {
                stream << "# +++ generated by kvpnc. Do not edit it." << "\n";
                stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";

                if (GlobalConfig->currentProfile->getSaveUserPassword())
                    GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserPassword();

                QString UsernameStr;
                if (!GlobalConfig->currentProfile->getDontSaveUsername())
                    UsernameStr = GlobalConfig->currentProfile->getUserName();
                else
                    UsernameStr = GlobalConfig->TmpUsername;

                GlobalConfig->appendLogEntry(i18n("Username: %1" , UsernameStr), KVpncEnum::debug);

                if (GlobalConfig->currentProfile->getUseNtDomainName() && !GlobalConfig->currentProfile->getNtDomainName().isEmpty()) {
                    // line: "<domainname>\\<username>"<tab><remote host><tab>"<password>"<tab><ip address>
                    stream << "\"" << GlobalConfig->currentProfile->getNtDomainName() << "\\\\" << UsernameStr << "\"\t" << "*" << "\t" << GlobalConfig->TmpPassword << "\t*\n";
                } else {
                    // line: "<username>"<tab><remote host><tab>"<password>"<tab><ip address>
                    stream << UsernameStr << "\t" << "*" << "\t" << "\"" << GlobalConfig->TmpPassword << "\"" << "\t*\n";
                }
                stream << "# --- generated by kvpnc. Do not edit it." << "\n";
                papSecretsFile.close();


                Utils(GlobalConfig, this).doChmod("/etc/ppp/pap-secrets", "go-rwx");
            }
        }
        if (do_auth) {
            Utils ( GlobalConfig, this ).doChmod ( "/etc/l2tpd/l2tp-secrets", "go-rwx" );

            // write xl2tpd /etc/l2tpd/l2tp-secrets
            QString L2tpSecrets = "/etc/l2tpd/l2tp-secrets"; // /etc/l2tpd/l2tp-secrets

            if ( GlobalConfig->KvpncDebugLevel > 0 )
                GlobalConfig->appendLogEntry ( i18n ( "l2tpd secrets file: %1" ).arg ( "/etc/l2tpd/l2tp-secrets" ), KVpncEnum::debug );
            QFile L2tpSecretsFile ( L2tpSecrets );
            stream.setDevice ( &L2tpSecretsFile );
            if ( L2tpSecretsFile.open ( IO_WriteOnly | IO_Append ) ) {
                stream << "# +++ generated by kvpnc. Do not edit it." << "\n";
                stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";

                if ( GlobalConfig->currentProfile->getSaveUserPassword() )
                    GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserPassword();

                QString UsernameStr;
                if ( !GlobalConfig->currentProfile->getDontSaveUsername() )
                    UsernameStr = GlobalConfig->currentProfile->getUserName();
                else
                    UsernameStr = GlobalConfig->TmpUsername;

                GlobalConfig->appendLogEntry ( i18n ( "Username: %1", UsernameStr ), KVpncEnum::debug );

                if ( GlobalConfig->currentProfile->getUseNtDomainName() && !GlobalConfig->currentProfile->getNtDomainName().isEmpty() ) {
                    // line: "<domainname>\\<username>"<tab><remote host><tab>"<password>"<tab><ip address>
                    stream << "\"" << GlobalConfig->currentProfile->getNtDomainName() << "\\\\" << UsernameStr << "\"\t" << "*" << "\t" << " \"" << GlobalConfig->TmpPassword << "\"\t*\n";
                } else {
                    // line: "<username>"<tab><remote host><tab>"<password>"<tab><ip address>
                    stream << "\"" << UsernameStr << "\"\t" << "*" << "\t" << " \"" << GlobalConfig->TmpPassword << "\"\t*\n";

                }
                stream << "# --- generated by kvpnc. Do not edit it." << "\n";
                L2tpSecretsFile.close();


                Utils ( GlobalConfig, this ).doChmod ( "/etc/l2tpd/l2tp-secrets", "go-rwx" );
            }
        }

    }
    if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp) {
        // write openl2tp.<profilename>.conf
        QString tmpPath = KStandardDirs::locateLocal("data", "kvpnc/");
        QString OpenL2tpContName = tmpPath + "openl2tp." + GlobalConfig->currentProfile->getName() + ".conf";
        QFile OpenL2tpConfigFile(OpenL2tpContName);
        QTextStream stream(&OpenL2tpConfigFile);
        if (OpenL2tpConfigFile.open(QIODevice::WriteOnly)) {
            stream << "# generated by kvpnc. Do not edit it." << "\n";
            stream << "# profile: " + GlobalConfig->currentProfile->getName() << "\n";
            stream << "" << "\n";
            stream << "ppp profile modify profile_name=default ";
            if (GlobalConfig->currentProfile->getAuthMethod() == "chap")
                stream << "auth_eap=no auth_pap=no auth_mschapv1=no auth_mschapv2=no";

            if (GlobalConfig->currentProfile->getAuthMethod() == "mschap")
                stream << "auth_eap=no auth_pap=no auth_mschapv1=yes auth_mschapv2=yes";

            if (GlobalConfig->currentProfile->getAuthMethod() == "mschap-v2")
                stream << "auth_eap=no auth_pap=no auth_mschapv1=no auth_mschapv2=yes";

            if (GlobalConfig->currentProfile->getAuthMethod() == "pap")
                stream << "auth_eap=no auth_pap=yes auth_mschapv1=no auth_mschapv2=no";

            stream << "\n";
            stream << "tunnel create tunnel_name=" << GlobalConfig->currentProfile->getName() << " dest_ipaddr="  << GlobalConfig->TmpGatewayIP << " persist=yes" << "\n";


            if (GlobalConfig->currentProfile->getSaveUserPassword())
                GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserPassword();

            QString UsernameStr;
            if (!GlobalConfig->currentProfile->getDontSaveUsername())
                UsernameStr = GlobalConfig->currentProfile->getUserName();
            else
                UsernameStr = GlobalConfig->TmpUsername;


            stream << "session create tunnel_name=" << GlobalConfig->currentProfile->getName() << " session_name=" << GlobalConfig->currentProfile->getName() << " user_name=" << UsernameStr << " user_password=" << GlobalConfig->TmpPassword << "\n";

            OpenL2tpConfigFile.close();


            if (!Utils(GlobalConfig, parent).loadKernelModule("slhc", parent)) {
                if (GlobalConfig->KvpncDebugLevel > 3)
                    GlobalConfig->appendLogEntry(i18n("Loading module \"%1\" failed." , QString("slhc"), QString("/etc/modprobe.conf")), KVpncEnum::debug);
                else if (GlobalConfig->KvpncDebugLevel > 3)
                    GlobalConfig->appendLogEntry(i18n("Loading module \"%1\" succeeded." , QString("slhc")), KVpncEnum::debug);
            }
            if (!Utils(GlobalConfig, parent).loadKernelModule("ppp_generic", parent)) {
                if (GlobalConfig->KvpncDebugLevel > 3)
                    GlobalConfig->appendLogEntry(i18n("Loading module \"%1\" failed." , QString("ppp_generic")), KVpncEnum::debug);
                else if (GlobalConfig->KvpncDebugLevel > 3)
                    GlobalConfig->appendLogEntry(i18n("Loading module \"%1\" succeeded." , QString("ppp_generic")), KVpncEnum::debug);
            }
            if (!Utils(GlobalConfig, parent).loadKernelModule("pppox", parent)) {
                if (GlobalConfig->KvpncDebugLevel > 3)
                    GlobalConfig->appendLogEntry(i18n("Loading module \"%1\" failed." , QString("pppox")), KVpncEnum::debug);
                else if (GlobalConfig->KvpncDebugLevel > 3)
                    GlobalConfig->appendLogEntry(i18n("Loading module \"%1\" succeeded." , QString("pppox")), KVpncEnum::debug);
            }
            if (!Utils(GlobalConfig, parent).loadKernelModule("pppol2tp", parent)) {
                if (GlobalConfig->KvpncDebugLevel > 3)
                    GlobalConfig->appendLogEntry(i18n("Loading module \"%1\" failed." , QString("pppol2tp")), KVpncEnum::debug);
                else if (GlobalConfig->KvpncDebugLevel > 3)
                    GlobalConfig->appendLogEntry(i18n("Loading module \"%1\" succeeded.", QString("pppol2tp")), KVpncEnum::debug);
            }

        } else {
            GlobalConfig->appendLogEntry(i18n("Creating %1 failed.", QString("openl2tp config file")), KVpncEnum::error);
            stopContinue = true;
        }
    }
}

void KVpnc::start_l2tpd()
{
    QString daemon = "";
    if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::l2tpd) {
        if (!GlobalConfig->pathToXl2tpd.isEmpty() && QFile(GlobalConfig->pathToXl2tpd).exists()) {
            if (GlobalConfig->KvpncDebugLevel > 1)
                GlobalConfig->appendLogEntry(i18n("Using %1.", QString("xl2tpd")), KVpncEnum::debug);
            daemon = "xl2tpd";
        } else {
            if (GlobalConfig->KvpncDebugLevel > 1)
                GlobalConfig->appendLogEntry(i18n("Using %1.", QString("l2tpd")), KVpncEnum::debug);
            daemon = "l2tpd";
        }

        QString L2tpdPid = "";
        if (daemon == "xl2tpd")
            L2tpdPid = "/var/run/xl2tpd.pid";
        else
            L2tpdPid = "/var/run/l2tpd.pid";


        QString L2tpdControl = "";
        if (daemon == "xl2tpd")
            L2tpdControl = "/var/run/l2tp-control";
        else
            L2tpdControl = "/var/run/l2tp-control";



//  if (QFile(L2tpdPid).exists())
//  {
//   if (GlobalConfig->KvpncDebugLevel > 1)
//    GlobalConfig->appendLogEntry(i18n("Using control interface for starting l2tp connection"),KVpncEnum::debug);
//
//   QString L2tpdControl="";
//   if (daemon == "xl2tpd")
//    L2tpdControl="/var/run/xl2tpd/l2tp-control";
//   else
//    L2tpdControl="/var/run/l2tp-control";
//
//   QFile L2tpdControlFile ( L2tpdControl );
//   QTextStream stream( &L2tpdControlFile );
//   if ( L2tpdControlFile.open( QIODevice::WriteOnly  ) ) {
//    stream << "c " << GlobalConfig->currentProfile->getName() << "\n";
//    L2tpdControlFile.close();
//   }
//   else
//   {
//    control_interface_success=false;
//    GlobalConfig->appendLogEntry(i18n("Starting l2tp connection via control interface has been failed"),KVpncEnum::error);
//   }
//  }
//  if (!QFile("/var/run/l2tpd.pid").exists() || control_interface_success==false)
        {
            if (GlobalConfig->KvpncDebugLevel > 1)
                GlobalConfig->appendLogEntry(i18n("Starting l2tpd manually"), KVpncEnum::debug);
            sleep(2);

            // start l2tpd
            L2tpdProcess = new QProcess(this);
            QString proc = "";
            QStringList args;
            if (daemon == "xl2tpd") {
                if (GlobalConfig->KvpncDebugLevel > 1)
                    GlobalConfig->appendLogEntry(i18n("Using %1.", QString("xl2tpd")), KVpncEnum::debug);
                proc = GlobalConfig->pathToXl2tpd;
            } else {
                if (GlobalConfig->KvpncDebugLevel > 1)
                    GlobalConfig->appendLogEntry(i18n("Using %1.", QString("l2tpd")), KVpncEnum::debug);
                proc = GlobalConfig->pathToL2tpd;
            }
            args.append("-p");
            args.append("/var/run/l2tpd." + GlobalConfig->currentProfile->getName() + ".pid");

            if (daemon == "xl2tpd") {
                args.append("-C");
                args.append(L2tpdControl);
            }
            args.append("-c");
            args.append(tmpPath + "l2tpd." + GlobalConfig->currentProfile->getName() + ".conf");
            //   args.append ( "-s" );
            //   args.append ( tmpPath + "l2tp-secrets." + GlobalConfig->currentProfile->getName() );
            args.append("-D");

            if (GlobalConfig->KvpncDebugLevel > 2) {
                if (GlobalConfig->KvpncDebugLevel > 1)
                    GlobalConfig->appendLogEntry("\"" + daemon + "\" cmd line: " + args.join(" ") , KVpncEnum::debug);
            }

            connect(L2tpdProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_l2tpd()));
            connect(L2tpdProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_l2tpd()));

            L2tpdProcess->setEnvironment(*env);
            L2tpdProcess->start(proc, args);
            if (!L2tpdProcess->waitForStarted()) {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , daemon), KVpncEnum::error);
                KMessageBox::error(this, i18n("Failed to start \"%1\"." , daemon));
                setGuiStatus(KVpncEnum::disconnected);
            } else {
                if (GlobalConfig->KvpncDebugLevel > 0)
                    GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString("l2tpd")), KVpncEnum::debug);


//    if (GlobalConfig->KvpncDebugLevel > 1)
//     GlobalConfig->appendLogEntry(i18n("Using control interface for starting l2tp connection"),KVpncEnum::debug);
//
//    QString L2tpdControl="";
//    if (daemon == "xl2tpd")
//     L2tpdControl="/var/run/xl2tpd/l2tp-control";
//    else
//     L2tpdControl="/var/run/l2tp-control";
//
//    QFile L2tpdControlFile ( L2tpdControl );
//    QTextStream stream( &L2tpdControlFile );
//    if ( L2tpdControlFile.open( QIODevice::WriteOnly  ) ) {
//     stream << "c " << GlobalConfig->currentProfile->getName() << "\n";
//     L2tpdControlFile.close();
//    }
//    else
//    {
//     control_interface_success=false;
//     GlobalConfig->appendLogEntry(i18n("Starting l2tp connection via control interface has been failed"),KVpncEnum::error);
//    }
            }
        }
    }
    if (GlobalConfig->currentProfile->getL2tpDaemon() == VpnAccountData::openl2tp) {
        {
            if (GlobalConfig->KvpncDebugLevel > 1)
                GlobalConfig->appendLogEntry(i18n("Using %1." , QString("openl2tp")), KVpncEnum::debug);
            daemon = "openl2tp";
        }

//   bool control_interface_success=true;

//   QString L2tpdPid="";
//   if (daemon == "xl2tpd")
//    L2tpdPid="/var/run/xl2tpd.pid";
//   else
//    L2tpdPid="/var/run/l2tpd.pid";

        startStopOpenl2tp(true);
        sleep(2);
        startStopOpenl2tp();

        if (GlobalConfig->KvpncDebugLevel > 1)
            GlobalConfig->appendLogEntry(i18n("Starting openl2tpd manually"), KVpncEnum::debug);
//   sleep ( 2 );

        // start openl2tpd
        OpenL2tpProcess = new QProcess(this);
        //
        if (GlobalConfig->KvpncDebugLevel > 1)
            GlobalConfig->appendLogEntry(i18n("Using %1.", QString("openl2tpd")), KVpncEnum::debug);

        QString proc = GlobalConfig->pathToOpenl2tp;
        QStringList args;

//    if (GlobalConfig->currentProfile->getConnectionType() == VpnAccountData::l2tpd_racoon)
//   {
//    // use ipsec tools extensions
//    args.append ( "-p" );
//    args.append ( "ipsec.so" );
//   }
        args.append("-f");    // foreground
        args.append("-c");

        QString tmpPath = KStandardDirs::locateLocal("data", "kvpnc/");
        QString OpenL2tpContName = tmpPath + "openl2tp." + GlobalConfig->currentProfile->getName() + ".conf";

        args.append(OpenL2tpContName);
        args.append("-D");    // debug

        if (GlobalConfig->KvpncDebugLevel > 2) {
            GlobalConfig->appendLogEntry("\"" + daemon + "\" cmd line: " + args.join(" ") , KVpncEnum::debug);
        }

        connect(OpenL2tpProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_openl2tp()));
        connect(OpenL2tpProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_openl2tp()));

        OpenL2tpProcess->setEnvironment(*env);
        OpenL2tpProcess->start(proc, args);
        if (!OpenL2tpProcess->waitForStarted()) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." , QString(daemon)), KVpncEnum::error);
            KMessageBox::error(this, i18n("Failed to start \"%1\".", QString(daemon)));
            setGuiStatus(KVpncEnum::disconnected);
        } else {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("\"%1\" started." , QString("openl2tp")), KVpncEnum::debug);
        }


    }
}

void KVpnc::checkL2tpPppUp()
{

    GlobalConfig->appendLogEntry(i18n("Check ppp device..."), KVpncEnum::debug);
    QString tmpPath = KStandardDirs::locateLocal("data", "kvpnc/");
    QFile L2tpPppPidFile("/var/run/ppp-kvpnc." + GlobalConfig->currentProfile->getName() + ".pid");

    if (L2tpPppPidFile.exists()) {
        if (L2tpPppPidFile.open(QIODevice::ReadOnly)) {
            L2tpPppDevice = "";
            QStringList contentlist = QString(L2tpPppPidFile.readAll()).split("\n");
            for (int i = 0; i < contentlist.size(); ++i) {
                QString line = contentlist.at(i);
                if (line.contains("ppp", Qt::CaseInsensitive)) {
                    L2tpPppDevice = line.trimmed();
                    break;
                }
            }

            L2tpPppPidFile.close();
            if (L2tpPppDevice.length() > 1) {

                // ok, we got the device

                if (GlobalConfig->KvpncDebugLevel >  2)
                    GlobalConfig->appendLogEntry(i18n("Tunnel device: %1\n", QString(L2tpPppDevice)), KVpncEnum::debug);

                L2tpWaitForPppUpTimer.stop();
                bool connectSuccess = false;

                NetworkInterface iface(GlobalConfig, parent);
                if (iface.interfaceExist(L2tpPppDevice)) {
                    TunnelInterfaceIP = iface.getInterfaceIP(L2tpPppDevice);
                    if (!TunnelInterfaceIP.isEmpty())
                        GlobalConfig->appendLogEntry(i18n("Tunnel interface IP address: %1\n" , QString(TunnelInterfaceIP)), KVpncEnum::debug);
                }


                if (TunnelInterfaceIP.isEmpty()) {
                    sleep(10);
                    if (iface.interfaceExist(L2tpPppDevice)) {
                        TunnelInterfaceIP = iface.getInterfaceIP(L2tpPppDevice);
                        if (!TunnelInterfaceIP.isEmpty())
                            GlobalConfig->appendLogEntry(i18n("Tunnel interface IP address: %1\n", QString(TunnelInterfaceIP)), KVpncEnum::debug);
                        if (!TunnelInterfaceIP.isEmpty()) {
                            connectSuccess = true;
                        }
                    }
                } else {
                    connectSuccess = true;
                }

                if (connectSuccess) {
                    sec = hour = min = 0;

                    GlobalConfig->status = KVpncEnum::connected;

                    disconnect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));
                    connect(&durationTimer, SIGNAL(timeout()), this, SLOT(slotDurationEvent()));
                    durationTimer.start(1000);
                    setGuiStatus(KVpncEnum::connected);


                    setFirewallAfterConnect();
                    if (GlobalConfig->currentProfile->getExecuteCmdAfterConnect())
                        executeCommandAfterConnect();

                    sleep(2);

                    if (GlobalConfig->currentProfile->getUseAdditionalNetworkRoutes() && !GlobalConfig->currentProfile->getAdditionalNetworkRoutes().isEmpty())
                        addAdditionalNetworkRoutes();

                    if (GlobalConfig->currentProfile->getUseConnectionStatusCheck()) {
                        startConnectionStatusCheck();
                    }

                }
            }

        }
//   else
//   {
//
//   }
    }

}

bool KVpnc::checkCiscoVpncStatus()
{
    ciscoVpncRunning = false;
    TestCiscoVpncProcess = new QProcess(this);
    TestCiscoVpncProcess->setProcessChannelMode(QProcess::MergedChannels);
    TestCiscoVpncProcess->setEnvironment(*env);
    QString proc = GlobalConfig->InterpreterShell;
    QStringList args;
    args.append("/etc/init.d/vpnclient_init");
    args.append("status");

    connect(TestCiscoVpncProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readCiscoVpncTestProcessOutput()));
    connect(TestCiscoVpncProcess, SIGNAL(readyReadStandardError()), this, SLOT(readCiscoVpncTestProcessOutput()));

    TestCiscoVpncProcess->setEnvironment(*env);
    TestCiscoVpncProcess->start(proc, args);
    if (!TestCiscoVpncProcess->waitForStarted()) {
        disconnect(TestCiscoVpncProcess, SIGNAL(readyReadStdout()), this, SLOT(readCiscoVpncTestProcessOutput()));
        disconnect(TestCiscoVpncProcess, SIGNAL(readyReadStderr()), this, SLOT(readCiscoVpncTestProcessOutput()));
        delete TestCiscoVpncProcess;
        TestCiscoVpncProcess = 0L;
        GlobalConfig->appendLogEntry(i18n("unable to start proc (%1)." , i18n("Test Cisco vpnclient")) , KVpncEnum::error);
        return false;
    } else {
        waitForFinished(TestCiscoVpncProcess, 100);
        disconnect(TestCiscoVpncProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readCiscoVpncTestProcessOutput()));
        disconnect(TestCiscoVpncProcess, SIGNAL(readyReadStandardError()), this, SLOT(readCiscoVpncTestProcessOutput()));
        delete TestCiscoVpncProcess;
        TestCiscoVpncProcess = 0L;
    }
    return ciscoVpncRunning;
}

void KVpnc::startCiscoVpnc()
{
    TestCiscoVpncProcess = new QProcess(this);
    TestCiscoVpncProcess->setProcessChannelMode(QProcess::MergedChannels);
    TestCiscoVpncProcess->setEnvironment(*env);
    QString proc = GlobalConfig->InterpreterShell;
    QStringList args;
    args.append("/etc/init.d/vpnclient_init");
    args.append("start");

    // connect ( TestCiscoVpncProcess, SIGNAL ( readyReadStandardOutput() ), this, SLOT ( readCiscoVpncTestProcessOutput() ) );
    // connect ( TestCiscoVpncProcess, SIGNAL ( readyReadStandardError() ), this, SLOT ( readCiscoVpncTestProcessOutput() ) );

    TestCiscoVpncProcess->setEnvironment(*env);
    TestCiscoVpncProcess->start(proc, args);
    if (!TestCiscoVpncProcess->waitForStarted()) {
        //  disconnect ( TestCiscoVpncProcess, SIGNAL ( readyReadStandardOutput() ), this, SLOT ( readCiscoVpncTestProcessOutput() ) );
        //  disconnect ( TestCiscoVpncProcess, SIGNAL ( readyReadStandardError() ), this, SLOT ( readCiscoVpncTestProcessOutput() ) );
        delete TestCiscoVpncProcess;
        TestCiscoVpncProcess = 0L;

        GlobalConfig->appendLogEntry(i18n("unable to start proc (%1)." , i18n("Start Cisco vpnclient")) , KVpncEnum::error);
        return;
    } else {
        if (GlobalConfig->KvpncDebugLevel > 1)
            GlobalConfig->appendLogEntry(i18n("proc (%1) started." , i18n("Start Cisco vpnclient")) , KVpncEnum::debug);
        waitForFinished(TestCiscoVpncProcess, 100);

//  disconnect ( TestCiscoVpncProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readCiscoVpncTestProcessOutput() ) );
//  disconnect ( TestCiscoVpncProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readCiscoVpncTestProcessOutput() ) );
        delete TestCiscoVpncProcess;
        TestCiscoVpncProcess = 0L;
    }
}

void KVpnc::sendFeedbackMail()
{
    FeedbackDialog = new KFeedbackDialog("crissi99@gmx.de", "feedback_mail");
    connect(FeedbackDialog->form(), SIGNAL(mailSent()), this, SLOT(feedbackMailSent()));

    KFeedbackQuestionList * list = FeedbackDialog->form()->questionList();

    KFeedbackQuestion * question = list->addQuestion(i18n("What is your general opinion about this program?"), "general_opinion", true, true);

    question->addAnswer(i18n("It is one of my favorites"), "1/8_favourite");
    question->addAnswer(i18n("I like it"), "2/8_like_it");
    question->addAnswer(i18n("It is sometimes useful"), "3/8_sometimes_useful");
    question->addAnswer(i18n("It is average"), "4/8_average");
    question->addAnswer(i18n("Nice try, but this could be done better"), "5/8_nice_try");
    question->addAnswer(i18n("It is poor"), "6/8_poor");
    question->addAnswer(i18n("It is useless"), "7/8_useless");
    question->addAnswer(i18n("It is terrible"), "8/8_crap");

    question = list->addQuestion(i18n("Which features of this program do you like?"), "features_liked", false);
    addFeatureList(question);

    question = list->addQuestion(i18n("Which features do you not like?"), "features_not_liked", false);
    addFeatureList(question);

    question = list->addQuestion(i18n("Which features do you never use?"), "features_never_used", false);
    addFeatureList(question);

    question = list->addQuestion(i18n("What is your favorite feature?"), "favourite_feature", true);
    addFeatureList(question);

    question = list->addQuestion(i18n("Are there features you are missing?"), "features_missing", true);
    question->addAnswer(i18n("Yes, a lot! (please add comment below)"), "1/4_lots");
    question->addAnswer(i18n("Some (please add comment below)"), "2/4_some");
    question->addAnswer(i18n("None"), "3/4_none");
    question->addAnswer(i18n("It has too many features already."), "4/4_too_many_already");

    question = list->addQuestion(i18n("How do you rate the stability of this program?"), "stability", true, true);
    question->addAnswer(i18n("Rock solid"), "1/5_rock_solid");
    question->addAnswer(i18n("Good"), "2/5_good");
    question->addAnswer(i18n("Average"), "3/5_average");
    question->addAnswer(i18n("Poor"), "4/5_poor");
    question->addAnswer(i18n("It keeps crashing all the time"), "5/5_keeps_crashing");

    question = list->addQuestion(i18n("How do you rate the performance of this program?"), "performance", true);
    question->addAnswer(i18n("Great"), "1/5_great");
    question->addAnswer(i18n("Good"), "2/5_good");
    question->addAnswer(i18n("Average"), "3/5_average");
    question->addAnswer(i18n("Poor"), "4/5_poor");
    question->addAnswer(i18n("It is so slow it drives me nuts"), "5/5_drives_me_nuts");

    question = list->addQuestion(i18n("What is your experience with computers in general?"), "computer_experience", true);
    question->addAnswer(i18n("Expert"), "1/5_expert");
    question->addAnswer(i18n("Fair"), "2/5_fair");
    question->addAnswer(i18n("Average"), "3/5_average");
    question->addAnswer(i18n("Learning"), "4/5_learning");
    question->addAnswer(i18n("Newbie"), "5/5_newbie");

    question = list->addQuestion(i18n("What is your experience with Unix/Linux systems?"), "unix_experience", true);
    question->addAnswer(i18n("Expert"), "1/5_expert");
    question->addAnswer(i18n("Fair"), "2/5_fair");
    question->addAnswer(i18n("Average"), "3/5_average");
    question->addAnswer(i18n("Learning"), "4/5_learning");
    question->addAnswer(i18n("Newbie"), "5/5_newbie");

    question = list->addQuestion(i18n("Did you have trouble figuring out how to work with this program in general?"),
                                 "learning_curve", true, true);
    question->addAnswer(i18n("No problem"), "1/5_no_problem");
    question->addAnswer(i18n("Some"), "2/5_some_problems");
    question->addAnswer(i18n("I am still learning"), "3/5_still_learing");
    question->addAnswer(i18n("I did not have a clue what to do at first"), "4/5_no_clue_at_first");
    question->addAnswer(i18n("I still do not have a clue what to do"), "5/5_still_no_clue");

    question = list->addQuestion(i18n("Where do you use this program most?"), "usage_where", true);
    question->addAnswer(i18n("At work"), "at_work");
    question->addAnswer(i18n("At home"), "at_home");
    question->addAnswer(i18n("At university / school"), "university");

    question = list->addQuestion(i18n("What is your primary role there?"), "primary_role", true);
    question->addAnswer(i18n("Home user"), "home_user");
    question->addAnswer(i18n("Student"), "student");
    question->addAnswer(i18n("Educational (teacher / professor)"), "educational");
    question->addAnswer(i18n("Non-computer related work"), "non_computer");
    question->addAnswer(i18n("Developer"), "developer");
    question->addAnswer(i18n("System administrator"), "sysadmin");

    question = list->addQuestion(i18n("Do you have any other roles there?"), "other_roles", false);
    question->addAnswer(i18n("Home user"), "home_user");
    question->addAnswer(i18n("Student"), "student");
    question->addAnswer(i18n("Educational (teacher / professor)"), "educational");
    question->addAnswer(i18n("Non-computer related work"), "non_computer");
    question->addAnswer(i18n("Developer"), "developer");
    question->addAnswer(i18n("System administrator"), "sysadmin");

    question = list->addQuestion(i18n("How did you get to know this program?"), "first_contact", true);
    question->addAnswer(i18n("In a menu on my machine"), "menu");
    question->addAnswer(i18n("Somebody told me about it"), "told");
    question->addAnswer(i18n("On the Internet"), "internet");
    question->addAnswer(i18n("Printed magazine / book"), "print_media");
    question->addAnswer(i18n("Other (please add comment below)"), "other");

    list->addYesNoQuestion(i18n("Would you recommend this program to a friend?"), "recommend", true);

    if (! FeedbackDialog->isVisible())
        FeedbackDialog->show();
}

void KVpnc::addFeatureList(KFeedbackQuestion *)
{
    //     question->addAnswer( i18n( "The directory tree display in general"   ), "tree_view"  );
    //     question->addAnswer( i18n( "Percentage bars as graphical display of relative sizes" ), "percentage_bars"  );
    //     question->addAnswer( i18n( "Files apart from directories in a separate <Files> item"), "files_item"  );

}

void KVpnc::feedbackMailSent()
{
    GlobalConfig->feedbackMailSent = true;
}

void KVpnc::waitForFinished(QProcess *process, int refreshtime, QString refreshmsg)
{
    if (process == 0L)
        return;

    while (process != 0L && process->state() == QProcess::Running) {
        usleep(refreshtime);
        if (!refreshmsg.isEmpty())
            if (GlobalConfig->KvpncDebugLevel > 2)
                GlobalConfig->appendLogEntry(refreshmsg, KVpncEnum::debug);
        if (GlobalConfig->appPointer->hasPendingEvents())
            GlobalConfig->appPointer->processEvents();
    }
}

// --- DBUS stuff ---
QString KVpnc::getVersion()
{
    QDBusMessage message;
    message << KGlobal::mainComponent().aboutData()->version();
    QDBusReply<QString> reply = message;
    return reply;
}

void KVpnc::doConnect()
{
    connectClicked();
}

void KVpnc::doDisconnect()
{
    disconnectClicked();
}

uint KVpnc::getConnectedTime()
{
    uint val = 0;
    if (GlobalConfig->status == KVpncEnum::connected) {
        // return secs
        val = hour * 60 * 60 + min * 60 + sec;
    }
    QDBusMessage message;
    message << val;
    QDBusReply<uint> reply = message;
    return reply;
}

QString KVpnc::getStatus()
{
    QString status = "unknown";
    if (GlobalConfig->status == KVpncEnum::connected)
        status = "connected";
    else if (GlobalConfig->status == KVpncEnum::disconnected)
        status = "disconnected";
    else if (GlobalConfig->status == KVpncEnum::connecting)
        status = "connecting";
    QDBusMessage message;
    message << status;
    QDBusReply<QString> reply = message;
    return reply;
}

QString KVpnc::getCurrentProfile()
{
    QDBusMessage message;
    message << GlobalConfig->currentProfile->getName();
    QDBusReply<QString> reply = message;
    return reply;
}

void KVpnc::setProfile(QString profilename)
{
    for (int i = 0; i < GlobalConfig->AccountList->count(); i++) {
        if (GlobalConfig->AccountList->at(i) ->getName() == profilename) {
            sessionToggled(profilename);
            mw->SessionCombo->setCurrentItem(profilename);
            GlobalConfig->currentProfile = GlobalConfig->AccountList->at(i);
            break;
        }
    }
}

void KVpnc::createNewProfile()
{
    newSessionClicked();
}

void KVpnc::createNewProfileWithWizard()
{
    showNewProfileWizardClicked();
}

void KVpnc::deleteCurrentProfile()
{
    deleteSessionClicked();
}

void KVpnc::openPreferences()
{
    slotSettings();
}

void KVpnc::doImportCert()
{
    importCertClicked();
}

void KVpnc::doImportPcf()
{
    importProfileClicked("");
}

void KVpnc::doImportPcf(QString file)
{
    importProfileClicked(file);
}

void KVpnc::doImportOpenvpnConfig()
{
    importOpenvpnProfileClicked("");
}

void KVpnc::doImportOpenvpnConfig(QString file)
{
    importOpenvpnProfileClicked(file);
}

QStringList KVpnc::profiles()
{
    QStringList profiles;
    VpnAccountData * it;
    if (!GlobalConfig->AccountList->isEmpty()) {
        for (int accountIdx = 0; accountIdx < GlobalConfig->AccountList->size(); ++accountIdx) {
            it = GlobalConfig->AccountList->at(accountIdx);
            profiles.append(it->getName());
        }
    }
    QDBusMessage message;
    message << profiles;
    QDBusReply<QStringList> reply = message;
    return reply;
}

void KVpnc::doQuit()
{
    quitCalled();
}

QStringList KVpnc::toolinfo()
{
    QStringList toolinfo;
    ToolInfo *tool = 0;
    for (int toolIdx = 0; toolIdx < GlobalConfig->ToolList->size(); ++toolIdx) {
        tool = GlobalConfig->ToolList->at(toolIdx);
        QString toolstring;
        QString state = "";
        QString usability = "";
        QString comment = "";

        //FIXME how it could be better?
        if (tool->Name == "vpnc") {
            if (!GlobalConfig->pathToVpnc.isEmpty()) {
                tool->addSearchPath(GlobalConfig->pathToVpnc.section('/', 0, -2));
                tool->collectToolInfo();
            }
        } else if (tool->Name == "ipsec") {
            if (!GlobalConfig->pathToIpsec.isEmpty()) {
                tool->addSearchPath(GlobalConfig->pathToIpsec.section('/', 0, -2));
                tool->collectToolInfo(); // crash if enabled (why the hell?)
            }
        } else if (tool->Name == "racoon") {
            if (!GlobalConfig->pathToRacoon.isEmpty()) {
                tool->addSearchPath(GlobalConfig->pathToRacoon.section('/', 0, -2));
                tool->collectToolInfo();
            }
        } else if (tool->Name == "setkey") {
            if (!GlobalConfig->pathToSetkey.isEmpty()) {
                tool->addSearchPath(GlobalConfig->pathToSetkey.section('/', 0, -2));
                tool->collectToolInfo();
            }
        } else if (tool->Name == "openvpn") {
            if (!GlobalConfig->pathToOpenvpn.isEmpty()) {
                tool->addSearchPath(GlobalConfig->pathToOpenvpn.section('/', 0, -2));
                tool->collectToolInfo();
            }
        } else if (tool->Name == "openssl") {
            if (!GlobalConfig->pathToOpenssl.isEmpty()) {
                tool->addSearchPath(GlobalConfig->pathToOpenssl.section('/', 0, -2));
                tool->collectToolInfo();
            }
        } else if (tool->Name == "pppd") {
            if (!GlobalConfig->pathToPppd.isEmpty()) {
                tool->addSearchPath(GlobalConfig->pathToPppd.section('/', 0, -2));
                tool->collectToolInfo();
            }

        } else if (tool->Name == "iptables") {
            if (!GlobalConfig->pathToIptables.isEmpty()) {
                tool->addSearchPath(GlobalConfig->pathToIptables.section('/', 0, -2));
                tool->collectToolInfo();
            }
        } else if (tool->Name == "kill") {
            if (!GlobalConfig->pathToKill.isEmpty()) {
                tool->addSearchPath(GlobalConfig->pathToKill.section('/', 0, -2));
                tool->collectToolInfo();
            }
        } else if (tool->Name == "killall") {
            if (!GlobalConfig->pathToKillall.isEmpty()) {
                tool->addSearchPath(GlobalConfig->pathToKillall.section('/', 0, -2));
                tool->collectToolInfo();
            }
        } else if (tool->Name == "ping") {
            if (!GlobalConfig->pathToPing.isEmpty()) {
                tool->addSearchPath(GlobalConfig->pathToPing.section('/', 0, -2));
                tool->collectToolInfo();
            }
        } else if (tool->Name == "ip") {
            if (!GlobalConfig->pathToIp.isEmpty()) {
                tool->addSearchPath(GlobalConfig->pathToIp.section('/', 0, -2));
                tool->collectToolInfo();
            }
        } else if (tool->Name == "ifconfig") {
            if (!GlobalConfig->pathToIfconfig.isEmpty()) {
                tool->addSearchPath(GlobalConfig->pathToIfconfig.section('/', 0, -2));
                tool->collectToolInfo();
            }
        } else if (tool->Name == "route") {
            if (!GlobalConfig->pathToRoute.isEmpty()) {
                tool->addSearchPath(GlobalConfig->pathToRoute.section('/', 0, -2));
                tool->collectToolInfo();
            }
        }

        if (!tool->PathToExec.isEmpty()) {
            state = i18n("Found");
            if (tool->Name == "vpnc") {
                if (tool->Version.indexOf("3.3", 0, Qt::CaseInsensitive) > -1) {
                    usability = i18n("full");
                } else if (tool->Version.indexOf("3.2", 0, Qt::CaseInsensitive) > -1) {
                    usability = i18n("limited");
                    comment = i18n("no split DNS support");
                } else if (tool->Version.indexOf("2.", 0, Qt::CaseInsensitive) > -1) {
                    usability = i18n("basic");
                    comment = i18n("no NAT-T, IPSec over IP, no split DNS support");
                }
            } else if (tool->Name == "freeswan") {
                if (tool->Version.indexOf("2.", 0, Qt::CaseInsensitive) > -1)
                    usability = i18n("full");
                else if (tool->Version.indexOf("1.", 0, Qt::CaseInsensitive) > -1)
                    usability = i18n("limited");
            } else if (tool->Name == "racoon") {
                //if ( tool->Version.indexOf("2.",0,-1) > -1)
                usability = i18n("full");
                //else if ( tool->Version.indexOf("2.",0,-1) > -1)
                // usability=i18n("limited");
            } else if (tool->Name == "openvpn") {
                if (tool->Version.indexOf("2.", 0, Qt::CaseInsensitive) > -1) {
                    usability = i18n("full");
                    int major = tool->Version.section('.', 0, 0).toInt();
                    int minor = tool->Version.section('.', 1, 1).toInt();
                    //     int subminor=tool->Version.section('.',2,2).toInt();

                    if (major >= 2 && minor >= 1)
                        usability += ", " + i18n("pcks11 support");
                } else if (tool->Version.indexOf("1.", 0, Qt::CaseInsensitive) > -1)
                    //else
                    usability = i18n("limited");
            } else if (tool->Name == "pppd") {
                //if ( tool->Version.indexOf("2.",0,-1) > -1)
                usability = i18n("full");
                //else if ( tool->Version.indexOf("2.",0,-1) > -1)
                // usability=i18n("limited");
            } else if (tool->Name == "kill") {
                //if ( tool->Version.indexOf("2.",0,-1) > -1)
                usability = i18n("full");
                //else if ( tool->Version.indexOf("2.",0,-1) > -1)
                // usability=i18n("limited");
            } else if (tool->Name == "ip") {
                //if ( tool->Version.indexOf("2.",0,-1) > -1)
                usability = i18n("full");
                //else if ( tool->Version.indexOf("2.",0,-1) > -1)
                // usability=i18n("limited");
            } else if (tool->Name == "ifconfig") {
                //if ( tool->Version.indexOf("2.",0,-1) > -1)
                usability = i18n("full");
                //else if ( tool->Version.indexOf("2.",0,-1) > -1)
                // usability=i18n("limited");
            } else if (tool->Name == "route") {
                //if ( tool->Version.indexOf("2.",0,-1) > -1)
                usability = i18n("full");
                //else if ( tool->Version.indexOf("2.",0,-1) > -1)
                // usability=i18n("limited");
            } else {
                // other tools
                usability = i18n("full");
            }
        } else {
            state = i18n("Not found");
            usability = i18n("none");
        }

        toolstring += tool->Name;
        toolstring += ",";
        toolstring += state;
        toolstring += ",";
        toolstring += tool->Version;
        toolstring += ",";
        toolstring += usability;
        toolstring += ",";
        toolstring += comment;

        toolinfo.append(toolstring);

    }

    QDBusMessage message;
    message << toolinfo;
    QDBusReply<QStringList> reply = message;
    return reply;
}

void KVpnc::doGenerateOpenvpnKey()
{
    generateOpenvpnKey();
}

void KVpnc::doSendFeedbackMail()
{
    sendFeedbackMail();
}

QStringList KVpnc::getProfileTypes()
{
    QStringList ProfileTypes;

    ProfileTypes.append("Cisco (vpnc)");
    ProfileTypes.append("IPSec (racoon)");
    ProfileTypes.append("IPSec (FreeSWAN/Openswan/strongSwan)");
    ProfileTypes.append("PPTP");
    ProfileTypes.append("OpenVPN");
    ProfileTypes.append("L2TP (racoon)");
    ProfileTypes.append("L2TP (freeswan)");
    ProfileTypes.append("Vtun");
    ProfileTypes.append("SSH");
    QDBusMessage message;
    message << ProfileTypes;
    QDBusReply<QStringList> reply = message;
    return reply;
}
