/*****************************************************************************
 * Copyright (C) 2010 S.R.Haque <srhaque@theiet.org>                         *
 * Christoph Thielecke <crissi99@gmx.de> (contains code from kvpnc.cpp)      *
 *                                                                           *
 * 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 <QtCore/QProcess>
#include <klocale.h>
#include <kmessagebox.h>
#include <kprocess.h>
#include <kptyprocess.h>
#include <kstandarddirs.h>
#include <unistd.h>
#include "CiscoVpncHandler.h"
#include "enterpassworddialog.h"
#include "enterxauthinteractivepasscodedialog.h"
#include "kvpnc.h"
#include "kvpncconfig.h"
#include "utils.h"

CiscoVpncHandler::CiscoVpncHandler(
    KVpnc *ui,
    KVpncConfig *config):
        HandlerBase(ui, config, "Cisco (free)", "vpnc", false),
        VpncConnectScript(""),
        VpncScript(""),
        vpncConfig(""),
        VpncDisconnectScript(""),
        VpncPty(0),
        VpncProcess(0),
        m_tool("vpnc", "0.3", ".|-")
{
    ToolInfo *info = Utils(GlobalConfig).getToolInfo(m_tool.name());
    if (!info->Version.isEmpty()) {
        // Typical version information:
        //
        // vpnc version 0.5.3
        // Copyright (C) 2002-2006 Geoffrey Keating, Maurice Massar, others
        // vpnc comes with NO WARRANTY, to the extent permitted by law.
        // You may redistribute copies of vpnc under the terms of the GNU General
        // Public License.  For more information about these matters, see the files
        // named COPYING.
        // Built with certificate support.
        //
        // Supported DH-Groups: nopfs dh1 dh2 dh5
        // Supported Hash-Methods: md5 sha1
        // Supported Encryptions: null des 3des aes128 aes192 aes256
        // Supported Auth-Methods: psk psk+xauth hybrid(rsa)
        m_tool.setActualVersion(info->Version);
    }
    if (GlobalConfig->currentProfile->getUseDnsUpdate()) {
        setenv("DNS_UPDATE", "Yes", 1);
        *env << "DNS_UPDATE=Yes";
    } else {
        setenv("DNS_UPDATE", "NO", 1);
        *env << "DNS_UPDATE=NO";
    }

}

bool CiscoVpncHandler::vpnStart(bool authenticationRetry)
{
    // Everything step of our logic is guarded by the error state. The error
    // state starts as zero for no error, and is set to the line where any
    // problem is caught.
    unsigned errorLine = 0;

    if (!errorLine) {
        // looking for vpnc
        if (!Utils(GlobalConfig).getToolInfo(m_tool.name())->found) {
            reportError(i18n("Unable to find \"%1\" at \"%2\".", m_tool.name(), GlobalConfig->pathToVpnc));
            errorLine = __LINE__;
        } else {
            debugMessage(0, i18n("Found helper %1 at %2", m_tool.name(), GlobalConfig->pathToVpnc));
        }
    }

    if (!errorLine) {
        if (!m_tool.isGe()) {
            reportError(i18n("%1 version %2 is too old. Minimum requirement is %3.", m_tool.name(), m_tool.minimumVersion(), m_tool.actualVersion()));
            errorLine = __LINE__;
        }
    }

    if (!errorLine) {
        GlobalConfig->TmpGatewayIP = Utils(GlobalConfig, kapp).resolveName(GlobalConfig->currentProfile->getGateway());
        if (GlobalConfig->TmpGatewayIP == "0.0.0.0" || GlobalConfig->TmpGatewayIP.isEmpty()) {
            reportError(i18n("Host \"%1\" could not be resolved." , GlobalConfig->currentProfile->getGateway()));
            errorLine = __LINE__;
        } else {
            debugMessage(0, i18n("Gateway hostname (%1) resolved to \"%2\"." , GlobalConfig->currentProfile->getGateway() , GlobalConfig->TmpGatewayIP));
        }
    }

    if (!errorLine) {
        if (!getAuthenticationData(authenticationRetry)) {
            errorMessage(i18n("Authentication data dialog cancelled."));
            errorLine = __LINE__;
        }
    }

    if (!errorLine) {
        if (!enableTunnelSupport()) {
            errorLine = __LINE__;
        }
    }

    if (!errorLine) {
        if (GlobalConfig->currentProfile->getExecuteCmdBeforeConnect()) {
            executeCommandBeforeConnect();
        }
    }

    if (!errorLine) {
        if (GlobalConfig->currentProfile->getID().isEmpty()) {
            reportError(i18n("%1 is empty. Please go to profile settings and enter %2." , i18n("VPN ID") , i18n("VPN ID")));
            errorLine = __LINE__;
        }
    }

    QString tmpInterface;
    if (!errorLine) {
        QString LocalIP;
        NetworkInterface iface(GlobalConfig, kapp);
        if (GlobalConfig->currentProfile->getNetworkDevice() == "default") {
            tmpInterface = iface.getDefaultInterface();
            debugMessage(0, i18n("Default interface: \"%1\"." , tmpInterface) );
            LocalIP = iface.getInterfaceIP(iface.getDefaultInterface());
            debugMessage(0, i18n("IP address of default interface: \"%1\"." , LocalIP) );
        } 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()) {
                debugMessage(0, i18n("No default interface found, using \"lo\"."));
                tmpInterface = "lo"; // no default interface found :(
                LocalIP = "127.0.0.1";
            } else {
                debugMessage(0, i18n("No default interface given, tried default interface, got success, using \"%1\"." , tmpInterface));
            }
        }

        if (LocalIP.isEmpty()) {
            debugMessage(0, i18n("No IP for default interface found, using \"127.0.0.1\"."));
            LocalIP = "127.0.0.1"; // no IP for default interface found :(
        }

        //   QString tunneldevice = "tun0";
        if (!backupDefaultRoute()) {
            errorLine = __LINE__;
        }
    }

    if (!errorLine) {
        QString 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>
        debugMessage(0, "VpncScript: " + VpncScript + "\n");
        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();
            debugMessage(3, i18n("Writing %1 finished.", VpncScript));
        } else {
            errorMessage(i18n("Creating %1 has been failed.", VpncScript));
            errorLine = __LINE__;
        }
    }

    if (!errorLine) {
        if (!Utils(GlobalConfig).doChmod(VpncScript, "+x"))  {
            VpncScript = tmpPath + "vpnc-script." + GlobalConfig->currentProfile->getName(); // vpnc-script.<name>
            errorMessage(i18n("Making %1 (%2) executable failed." , QString("VpncScript") , VpncScript));
            errorLine = __LINE__;
        }
    }

    QString VpncConfigFile;
    // FIXME maybe this as config option?
    bool force_vpnc_config_file = true;
    if (!errorLine) {
        debugMessage(3, i18n("Generating vpnc config"));

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


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

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

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

        // !ge(0.3.3) == le(0.3.2)
        if (!m_tool.actualIsGe("0.3.3") || force_vpnc_config_file ) {
            // write vpnc connect script
            debugMessage(1, "VpncConfig: " + VpncConfigFile + "\n");
            QFile configfile(VpncConfigFile);
            QTextStream configstream(&configfile);
            if (configfile.open(QIODevice::WriteOnly)) {
                configstream << vpncConfig << "\n";
                configfile.close();
            } else {
                reportError(i18n("Failed to create \"%1\"." , VpncConfigFile));
                errorLine = __LINE__;
            }
        }
    }

    if (!errorLine) {
        QStringList args;
        args.append("--script");
        args.append(VpncScript);

        // !ge(0.3.3) == le(0.3.2)
        if (!m_tool.actualIsGe("0.3.3")) {
            //                  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());
            debugMessage(0, i18n("Using (NT) domain name \"%1\"." , GlobalConfig->currentProfile->getNtDomainName()));
        }

        if (GlobalConfig->currentProfile->getUseNat() && GlobalConfig->currentProfile->getCiscoNatMode() != "none") {
            if (m_tool.actualIsGe("0.4")) {
                // TODO add other nat modes
                args.append("--natt-mode");
                args.append(GlobalConfig->currentProfile->getCiscoNatMode());
                debugMessage(0, i18n("Using NAT-T mode \"%1\"." , GlobalConfig->currentProfile->getCiscoNatMode()));
            } else
                args.append("--udp");

            debugMessage(0, i18n("Using UDP."));
        } else {
            if (m_tool.actualIsGe("0.4.1")) {
                args.append("--natt-mode");
                args.append("none");
            } else {
                args.append("--disable-natt");
            }
            debugMessage(0, i18n("Disabling NAT-T."));
        }

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


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


        if (GlobalConfig->currentProfile->getUseXauthInteractive() && m_tool.actualIsGe("0.3.2")) {
            args.append("--xauth-inter");
            debugMessage(0, i18n("Enabling interactive extended authentication (for challenge response auth)"));
        }

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


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


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

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

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

        if (m_tool.actualIsGe("0.4")) {
            args.append("--ifmode");
            if (GlobalConfig->currentProfile->getTunnelDeviceType() == "tap") {
                debugMessage(1, i18n("Using tunnel device type: %1." , QString("TAP")));
                args.append("tap");
            } else {
                debugMessage(1, i18n("Using tunnel device type: %1." , QString("TUN")));
                args.append("tun");
            }
        }
        if (GlobalConfig->currentProfile->getDisableDataEncryption() == true) {
            if (m_tool.actualIsGe("0.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 (m_tool.actualIsGe("0.5")) {
            if (GlobalConfig->currentProfile->getUseDpdIdleTimeout()) {
                args.append("--dpd-idle");
                args.append(QString().setNum(GlobalConfig->currentProfile->getDpdIdleTimeout()));
                debugMessage(1, i18n("Using DPD idle timeout: %1." , GlobalConfig->currentProfile->getDpdIdleTimeout()));
            } else {
                // disabling DPD (Dead Peer Detection)
                args.append("--dpd-idle");
                args.append("0");
                debugMessage(1, i18n("Disabling DPD idle timeout."));
            }
        }

        if (!m_tool.actualIsGe("0.3.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) {
                debugMessage(5, i18n("Forcing vpnc config in real file: \"%1\"." , VpncConfigFile));
                args.append(VpncConfigFile);
            } else {
                if (m_tool.actualIsGe("0.3.2")) {
                    // we send config via stdin
                    args.append("-");
                }
            }
        }

        debugMessage(0, i18n("Setting DNS_UPDATE \"%1\"." , QString(qgetenv("DNS_UPDATE"))));

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


        VpncProcess = new HelperPtyProcess(this, GlobalConfig->pathToVpnc, args, *env,
                                           SLOT(helperOutputReader()), SLOT(helperOutputReader()),
                                           SLOT(helperPtyReader()),
                                           0, 0);
        if (!VpncProcess)
        {
            errorLine = __LINE__;
        } else {
            VpncPty = VpncProcess->pty();
            if (!VpncProcess->start()) {
                errorLine = __LINE__;
            }
        }
    }

    if (!errorLine) {
        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();
            //              }

            debugMessage(2, i18n("Sending config to \"%1\"..." , QString("vpnc")));
            VpncPty->write(vpncConfig.toUtf8());
            //VpncProcess->write(vpncConfig.toUtf8());
            debugMessage(2, i18n("Config to \"%1\" sent." , QString("vpnc")));

        }
    }

    if (!errorLine) {
        debugMessage(0, 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()));
    } else {
        errorMessage(i18n("Error at line %1.", errorLine));
    }
    return 0 == errorLine;
} // vpnc

void CiscoVpncHandler::vpnStop()
{
    if (VpncProcess) {
        delete VpncProcess;
        VpncPty = 0;
        VpncProcess = 0;
    }

    //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();
    }
    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()) {
            debugMessage(0, i18n("Vpnc pid file found, killing process %1", QString(Vpnc_pid)) );
            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)
        //                             debugMessage(i18n("No vpnc pid file found, using \"killall\" for killing vpnc."));
        //                         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()) {
            debugMessage(2, i18n("Restoring default route before connection..."));

            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())
        //errorMessage(i18n("Restore of %1 has failed.", QString("")),KVpncEnum::error);

        stream << GlobalConfig->pathToIp + " route flush cache\n";
        file.close();
        disconnectProcess("vpnc_disconnect", VpncDisconnectScript);
    }
}

bool CiscoVpncHandler::getAuthenticationData(bool AuthRetry)
{
    bool askUsernamePass = false;

    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 {
        debugMessage(4, i18n("User data already collected."));
    }

    if (GlobalConfig->currentProfile->getAskUserPasswordOnEachConnect()) {
        debugMessage(4, i18n("User password on each connect forced."));

        askUsernamePass = true;
        requestUsername = true;
    }

    if (!askUsernamePass) {
        GlobalConfig->TmpPassword = GlobalConfig->currentProfile->getUserPassword();
        GlobalConfig->TmpGroupPassword = GlobalConfig->currentProfile->getPreSharedKey();
        GlobalConfig->TmpUsername = GlobalConfig->currentProfile->getUserName();
        return true;
    }

    // Show the dialog.
    EnterUsernamePasswordDialog dlg(gui, 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) {
            errorMessage(i18n("Group password is empty"));
            return false;
        }

        if (requestUsername && GlobalConfig->currentProfile->getUserName().isEmpty()) {
            errorMessage(i18n("Username is empty."));
            return false;
        }

        debugMessage(0, i18n("Some account data which was needed was obtained from a password dialog."));

        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 {
        debugMessage(0, i18n("Connect canceled because account data dialog aborted."));
        return false;
    }
    return true;
}

QString CiscoVpncHandler::pingDevice() const {
    return VpncDevice;
}

void CiscoVpncHandler::helperOutputReader()
{
    QStringList msg_list = QString(VpncProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        helperParser(msg, "[vpnc]");
    }
}

void CiscoVpncHandler::helperPtyReader()
{
    QStringList msg_list = QString(VpncPty->readAll()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString msg = msg_list.at(i);
        helperParser(msg, "[vpnc pty]");
    }
}

void CiscoVpncHandler::helperParser(QString msg, const QString &source)
{
    static bool deviceaddrstr2addr = true;
    QString deviceaddrstr;
    QString deviceaddr;
    bool connectSuccess = false;
    unsigned errorLine = 0;
    DisconnectionReason reason = DISCONNECTION_REASON_FATAL_ERROR;
    bool doContinue = true;
    //   mw->DebugOutput->append( "readOutputFrom_vpnc line:\n"+ProcessMsg_connect );
    if (deviceaddrstr2addr) {
        deviceaddrstr = msg;

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

    debugMessage(3, source + ": " + msg);

    //  // 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)
    //              debugMessage(i18n("Sending config to \"%1\"..." , QString("vpnc")));
    //
    //          sendingVpncConfigInProgress = true;
    //          VpncPty->write(vpncConfig.toUtf8());
    //          sendingVpncConfigInProgress = false;
    //
    //          if (GlobalConfig->KvpncDebugLevel > 2)
    //              debugMessage(i18n("Config to \"%1\" sent." , QString("vpnc")));
    //
    //      }
    //  }

    if (msg.indexOf("Enter IPSec secret for", 0, Qt::CaseInsensitive) > -1) {
        debugMessage(0, i18n("%1: Group password requested, send it...", source));

        QString GrpPassStr = GlobalConfig->TmpGroupPassword;

        debugMessage(4, i18n("%1: Group password: %2", source, GrpPassStr));

        VpncPty->write(GrpPassStr.toUtf8());
        VpncPty->write("\n");

    }

    // requesting password
    else if (msg.indexOf("password for", 0, Qt::CaseInsensitive) > -1) {
        debugMessage(0, i18n("%1: User password requested, send it...", source));

        QString UserPassStr = GlobalConfig->TmpPassword;

        debugMessage(4, i18n("%1: User password: %2", source, UserPassStr));

        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) {
        debugMessage(0, i18n("%1: IPSec gateway address requested, send it...", source));
        //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) {
        debugMessage(0, i18n("%1: IPSec ID requested, send it...", source));
        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) {
        debugMessage(0, i18n("%1: Username requested, send it...", source));
        QString UsernameStr = GlobalConfig->TmpUsername;
        VpncPty->write(UsernameStr.toUtf8());
        VpncPty->write("\n");
    }

    // using interface tun0
    else if (msg.indexOf("using interface", 0, Qt::CaseInsensitive) > -1) {
        VpncDevice = msg.section(' ', 2, 2);    // using interface tun0 -> tun0
        debugMessage(0, i18n("Tunnel device: %1\n" , VpncDevice));
    }

    //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 );
        gui->setTunnelInterfaceIP(msg.section(' ', 2, 2));
    }


    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)
        debugMessage(0, i18n("line: %1\n" , msg));

    else if (msg.indexOf("AUTHENTICATION_FAILED", 0, Qt::CaseInsensitive) > -1) {
        serverError(i18n("Authentication failed (%1)." , i18n("group password")));
        reason = DISCONNECTION_REASON_AUTHENTICATION_FAILED;
        errorLine = __LINE__;
    }

    //quick mode response rejected: (ISAKMP_N_INVALID_PAYLOAD_TYPE)(1)
    else if (msg.indexOf("quick mode response rejected:", 0, Qt::CaseInsensitive) > -1) {
        serverError(i18n("Connection rejected because wrong settings sent to the VPN server. Please check your settings.")) ;
        errorLine = __LINE__;
    }

    else if (msg.indexOf("authentication unsuccessful", 0, Qt::CaseInsensitive) > -1) {
        serverError(i18n("Authentication failed (%1)." , i18n("user password")));
        reason = DISCONNECTION_REASON_AUTHENTICATION_FAILED;
        errorLine = __LINE__;
    }

    // no ip for gateway
    else if (msg.indexOf("vpnc: unknown host `<Replace with your gateway IP address>' ", 0, Qt::CaseInsensitive) > -1) {
        serverError(i18n("You have to enter an IP address for the remote gateway."));
        errorLine = __LINE__;
    }

    // no answer
    else if (msg.indexOf("no response from target", 0, Qt::CaseInsensitive) > -1) {
        serverError(i18n("No response from VPN server"));
        errorLine = __LINE__;
    }

    // initalizing tunnel interface failed
    else if (msg.indexOf("can't initialise tunnel interface", 0, Qt::CaseInsensitive) > -1) {
        serverError(i18n("Tunnel interface cannot be initialized."));
        errorLine = __LINE__;
        doContinue = false;
    }

    // /dev/net/tun does not exist
    else if (msg.indexOf("can't open /dev/net/tun", 0, Qt::CaseInsensitive) > -1) {
        reportError(i18n("Device file \"%1\" cannot be opened." , QString("/dev/net/tun")));
        errorLine = __LINE__;
    }

    // host unknown
    else if (msg.indexOf("unknown host" , 0, Qt::CaseInsensitive) > -1) {
        serverError(i18n("Host unknown"));
        errorLine = __LINE__;
    }

    //socket creation failed
    else if (msg.indexOf("making socket", 0, Qt::CaseInsensitive) > -1) {
        serverError(i18n("Socket creation failed"));
        errorLine = __LINE__;
    }

    else if (msg.indexOf("receiving packet: Connection refused", 0, Qt::CaseInsensitive) > -1) {
        serverError(i18n("Connection to the Cisco server was refused"));
        errorLine = __LINE__;
    }

    // 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) {
        //   if ( GlobalConfig->KvpncDebugLevel > 0 )
        //    debugMessage( i18n( "Binding to port failed. Another vpnc is running, terminate it and try reconnect ." ) );
        //debugMessage(0, QString("binding" + ProcessMsg_connect));
        //   QFile oldpidfile( tmpPath + "vpnc-pid." + GlobalConfig->currentProfile->getName() + ".pid" );
        //   if (oldpidfile.exists())
        //   {
        //    if ( GlobalConfig->KvpncDebugLevel > 0 )
        //     debugMessage( i18n( "Old pid file found: %1" ,oldpidfile.name()) );
        //    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 )
        //      debugMessage( i18n( "Vpnc pid file contains a pid: %1, try to terminate the process with this pid." , Vpnc_pid ) );
        //     QString proc = GlobalConfig->pathToKill;
        //     QStringList args;
        //     args.append("-3");
        //     args.append(Vpnc_pid);
        //    }
        //    else
        //    {
        //     if ( GlobalConfig->KvpncDebugLevel > 0 )
        //      debugMessage( i18n( "No vpnc pid file found, using \"killall\" for killing vpnc." ) );
        //     args.append("-3");
        //
        //    }
        //
        //    args.append("vpnc");
        //    killvpncprocess.setEnvironment(*env);
        //    killvpncprocess.start(proc,args);
        //    if (!killvpncprocess.waitForStarted())
        //     errorMessage( 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())
        //     errorMessage( i18n( "%1 could not be killed." ,"vpnc") ,KVpncEnum::error);
        //
        //    killvpncprocess.waitForFinished();

        //    setStatusDisconnected(__LINE__);
        //    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 )
        //     debugMessage( i18n( "Old defaultroute file found: %1" ,OldDefaultroute) );
        //
        //
        //    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 )
        //       debugMessage( i18n( "Old resolv.conf file found, restore it." ) );
        //
        //      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 )
        //      debugMessage( i18n( "Disconnect script started." ) );
        //    }
        //    setStatusDisconnected(__LINE__);
        //    connectionEnded();
        //   }
        //
        //   if ( GlobalConfig->KvpncDebugLevel > 0 )
        //    debugMessage( i18n( "Trying reconnect..." ) );
        //
        //   connectClicked();

        QString NameAndPid = Utils(GlobalConfig).getNameAndPidOfProgramListen(500);
        debugMessage(0, i18n("NameAndPid: %1" , NameAndPid) );
        if (!NameAndPid.isEmpty()) {
            int pid = NameAndPid.section('/', 0, 0).toInt();
            QString Name = NameAndPid.section('/', 1, 1);
            serverError(i18n("Failed to bind to port %1 because program \"%2\" with PID \"%3\" is using it.", QString().setNum(500), Name, QString().setNum(pid)));
        } else
            serverError(i18n("Failed to bind to port %1 because another program is using it.", QString().setNum(500)));
        errorLine = __LINE__;
    }

    // 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 )
    //     debugMessage( i18n( "Binding to port failed. Another program is running at this port, terminate it and try reconnect ." ) );
    /*
    QFile oldpidfile( tmpPath + "vpnc-pid." + GlobalConfig->currentProfile->getName() + ".pid" );
    if (oldpidfile.exists())
    {
    debugMessage(0,  i18n( "Old pid file found: %1" ,oldpidfile.name()) );
        QTextStream pidFileStream( &oldpidfile );
        QString Vpnc_pid = "";
        if ( oldpidfile.open( QIODevice::ReadOnly ) )
        {
            Vpnc_pid = pidFileStream.readLine();
            oldpidfile.close();
        }
        QProcess killvpncprocess(this);
        if ( !Vpnc_pid.isEmpty() )
        {

    debugMessage(0,  i18n( "Vpnc pid file contains a pid: %1, try to terminate the process with this pid." , Vpnc_pid ) );
            QString proc = GlobalConfig->pathToKill;
            QStringList args;
            args.append("-3");
            args.append(Vpnc_pid);
        }
        else
        {
    debugMessage(0,  i18n( "No vpnc pid file found, using \"killall\" for killing vpnc." ) );
            args.append("-3");

        }

        args.append("vpnc");
        killvpncprocess.setEnvironment(*env);
        killvpncprocess.start(proc,args);
        if (!killvpncprocess.waitForStarted())
            errorMessage( 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())
            errorMessage( i18n( "%1 could not be killed." ,"vpnc") ,KVpncEnum::error);

        killvpncprocess.waitForFinished();


        //     setStatusDisconnected(__LINE__);
        //connectClicked();
        //    }
        */

    //   KMessageBox::error( this, i18n( "Address already in use" ) );
    //   errorMessage(i18n( "Address already in use" ) ,KVpncEnum::error);
    //   abort = true;
    //  }


    else if (msg.indexOf("Network is unreachable", 0, Qt::CaseInsensitive) > -1) {
        serverError(i18n("No network reachable"));
        errorLine = __LINE__;
    }


    else if (msg.indexOf("response was invalid", 0, Qt::CaseInsensitive) > -1 &&  msg.indexOf("ISAKMP_N_INVALID_EXCHANGE_TYPE", 0, Qt::CaseInsensitive) > -1) {
        serverError(i18n("Invalid ISAKMP exchange type received"));
        errorLine = __LINE__;
        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 );
        errorLine = __LINE__;
    }

    else if (msg.indexOf("Passcode for VPN", 0, Qt::CaseInsensitive) > -1) {
        //if (GlobalConfig->currentProfile->getUseXauthInteractive()) {
        GlobalConfig->TmpXauthInterPasscode = "";
        EnterXauthInteractivePasscodeDialog dlg(gui);
        dlg.setWindowTitle( i18n("Enter Xauth interactive passcode"));
        dlg.main->SavePasswordCheckBox->hide();
        debugMessage(0, i18n("%1: Passcode for Xauth interactive requested...", source));
        dlg.exec();
        if (!dlg.main->PasswordEdit->text().isEmpty()) {
            debugMessage(0, i18n("%1: Got passcode for Xauth interactive from enter Xauth interactive passcode dialog...", source));
            GlobalConfig->TmpXauthInterPasscode = dlg.main->PasswordEdit->text();

            debugMessage(0, i18n("%1: Send passcode for Xauth interactive...", source));
            VpncPty->write(GlobalConfig->TmpXauthInterPasscode.toUtf8());
            VpncPty->write("\n");
        }
        //}
    }

    else if (msg.indexOf("Connect Banner", 0 , Qt::CaseInsensitive) > -1) {
        debugMessage(0, i18n("%1: Connect banner received: %2", source, msg));
    }


    if (connectSuccess) {
        successMessage(i18n("%1: Connection established.", source));

        setStatusConnected(__LINE__);

        NetworkInterface iface(GlobalConfig, kapp);
        gui->setTunnelInterfaceIP(iface.getInterfaceIP(VpncDevice));
    }
    if (errorLine) {
        setStatusDisconnected(errorLine, reason);
    }
}
