File: ConnectionManager.cpp

package info (click to toggle)
l2tp-ipsec-vpn 1.0.9-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 1,396 kB
  • sloc: cpp: 9,952; xml: 400; makefile: 139; sh: 78
file content (697 lines) | stat: -rw-r--r-- 22,688 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
/*
 * $Id: ConnectionManager.cpp 144 2012-05-21 07:31:37Z wejaeger $
 *
 * File:   ConnectionManager.cpp
 * Author: Werner Jaeger
 *
 * Created on July 7, 2010, 5:44 PM
 *
 * Copyright 2010 Werner Jaeger.
 *
 * 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 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <unistd.h>

#include <QSystemTrayIcon>
#include <QAction>
#include <QMenu>
#include <QTimer>
#include <QMessageBox>
//#include <QDebug>

#include "pkcs11/SmartCardState.h"
#include "util/NetworkInterfaceMonitor.h"
#include "util/SecretsChecker.h"
#include "dialogs/ConnectionEditorDialog.h"
#include "dialogs/ConnectionInformationDialog.h"
#include "settings/ConnectionSettings.h"
#include "L2tpIPsecVpnApplication.h"
#include "ConnectionState.h"
#include "VPNControlTask.h"
#include "ConnectionManager.h"

/*!
    \class ConnectionManager

    \brief The ConnectionManager class manages L2TP over IPsec VPN connections.
*/

/*!
    Creates a new ConnectionManager object.
*/

static const int PTPINTERFACE_CHECK_UP_TIME(30000);
static const int PTPINTERFACE_CHECK_DOWN_TIME(30000);
static const int VPN_TASK_TIMOUT(80000);

static const QString strRuntimePath("/var/run/L2tpIPsecVpnControlDaemon/");
static const char* const strAbout(
   "<p><center><small>Copyright &copy; 2010-2012 Werner Jaeger</small></center></p>"
   "<p><center><a href='http://wiki.l2tpipsecvpn.tuxfamily.org/'>Help</a></center></p>"
   "<p><center><a href='https://launchpad.net/l2tp-ipsec-vpn'>Website</a></center></p>"
);

ConnectionManager::ConnectionManager(L2tpIPsecVpnApplication& application, QObject* pParent) : QObject(pParent), m_pConnectionInformation(new ConnectionInformationDialog()),
  m_pTimeout(new QTimer), m_pActions(new ActionList()), m_Application(application), m_pState(new NotConnected(NULL)), m_fIsExecuting(false), m_fRoutePriorityIsChanging(false)
{
   connect(&m_Application, SIGNAL(connectionAdded(const QString&)), SLOT(onConnectionAdded(const QString&)));
   connect(&m_Application, SIGNAL(connectionRemoved(const QString&)), SLOT(onConnectionRemoved(const QString&)));

   m_pTimeout->setInterval(VPN_TASK_TIMOUT);
   m_pTimeout->setSingleShot(true);
   connect(m_pTimeout, SIGNAL(timeout()), SLOT(onVpnTaskTimeout()));

   createActions();

   m_pVPNControlTask = new VPNControlTask(this);
   connect(m_pVPNControlTask, SIGNAL(commandOutputReceived(const QString&)), SLOT(onVpnTaskOutput(const QString&)));
   connect(m_pVPNControlTask, SIGNAL(readyReadLog()), SLOT(onVpnTaskReadyReadLog()));
   connect(m_pVPNControlTask, SIGNAL(errorMessageEmited(int)), SLOT(onVpnTaskErrorMsg(int)));
   connect(m_pVPNControlTask, SIGNAL(finished()), SLOT(onVpnTaskFinished()));
}

/*!
    Frees the resources associated with this ConnectionManager object.
*/
ConnectionManager::~ConnectionManager()
{
   NetworkInterfaceMonitor::instance()->stop();

   delete m_pConnectionInformation;

   while (!m_pActions->isEmpty())
      delete m_pActions->takeFirst();

   delete m_pTimeout;
   delete m_pActions;
   delete m_pState;
   delete m_pTrayIcon;
   delete m_pTrayIconMenu;
   delete m_pVPNControlTask;
}

int ConnectionManager::exec()
{
   int iRet(1);

   // at startup it might last few seconds until a tray is available, lets try a view times before giving up
   for (int i = 0; iRet != 0 && i < 30; i++)
   {
      if (QSystemTrayIcon::isSystemTrayAvailable())
         iRet = 0;
      else
         ::sleep(1);
   }

   if (iRet == 0)
   {
      createTrayIcon();
      updateContextMenu(true);

      const ConnectionSettings settings;
      const int iSize = settings.connections();
      for (int i = 0; i < iSize; i++)
         onConnectionAdded(settings.connection(i));

      m_pTrayIcon->show();

      QTimer::singleShot(100, this, SLOT(detectConnectionState()));

      iRet = m_Application.exec();
   }
   else
      QMessageBox::critical(NULL, m_Application.applicationName(), QObject::tr("I couldn't detect any system tray on this system."));

   return(iRet);
}

void ConnectionManager::createActions()
{
   m_pActions->insert(DISC, new QAction(tr("&Disconnect"), this));
   m_pActions->insert(EDIT, new QAction(tr("&Edit Connections ..."), this));
   m_pActions->insert(INFO, new QAction(tr("Connection &Information"), this));
   m_pActions->insert(ABOUT, new QAction(tr("&About"), this));
   m_pActions->insert(QUIT, new QAction(tr("&Quit"), this));

   connect(action(DISC), SIGNAL(triggered()), SLOT(vpnDisconnect()));
   connect(action(EDIT), SIGNAL(triggered()), SLOT(editConnections()));
   connect(action(INFO), SIGNAL(triggered()), SLOT(showConnectionInformation()));
   connect(action(ABOUT), SIGNAL(triggered()), SLOT(about()));
   connect(action(QUIT), SIGNAL(triggered()), &m_Application, SLOT(quit()));
}

void ConnectionManager::createTrayIcon()
{
   m_pTrayIconMenu = new QMenu();
   m_pTrayIconMenu->addAction(action(DISC));
   m_pTrayIconMenu->addSeparator();
   m_pTrayIconMenu->addAction(action(EDIT));
   m_pTrayIconMenu->addAction(action(INFO));
   m_pTrayIconMenu->addSeparator();
   m_pTrayIconMenu->addAction(action(ABOUT));
   m_pTrayIconMenu->addSeparator();
   m_pTrayIconMenu->addAction(action(QUIT));

   m_pTrayIcon = new QSystemTrayIcon(this);
   m_pTrayIcon->setContextMenu(m_pTrayIconMenu);

   m_pState = new NotConnected(m_pTrayIcon);

   connect(m_pTrayIconMenu, SIGNAL(triggered(QAction*)), SLOT(vpnConnect(QAction*)));
   connect(m_pTrayIcon, SIGNAL(messageClicked()), SLOT(messageClicked()));
   connect(m_pTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
}

void ConnectionManager::updateContextMenu(bool fStatusChanged)
{
   if (m_pState->isState(ConnectionState::Connected))
   {
      enableAllConnections(false);
      action(DISC)->setEnabled(true);
   }
   else if (m_pState->isState(ConnectionState::Connecting))
   {
      enableAllConnections(false);
      action(DISC)->setEnabled(true);
   }
   else if (m_pState->isState(ConnectionState::Disconnecting))
   {
      enableAllConnections(false);
      action(DISC)->setEnabled(false);
   }
   else if (m_pState->isState(ConnectionState::Error))
   {
      enableAllConnections(true);
      action(DISC)->setEnabled(NetworkInterface::defaultGateway().size() == 1);
   }
   else
   {
      enableAllConnections(NetworkInterface::defaultGateway().size() == 1);
      action(DISC)->setEnabled(false);
   }

   if (fStatusChanged)
   {
      m_pConnectionInformation->onConectionStateChanged(m_pState, m_pVPNControlTask->connectionName());
      showMessage();
   }
}

void ConnectionManager::vpnConnect(const QString& strConnectionName)
{
//   qDebug() << "ConnectionManager::vpnConnect(const QString&" << strConnectionName << ")";

   if (!m_fIsExecuting)
   {
      const SecretsChecker secrets(strConnectionName);

      if (secrets.check())
      {
         const PppSettings pppSettings(ConnectionSettings().pppSettings(strConnectionName));
         const bool fUseSmartCard = !pppSettings.refuseEap() && pppSettings.eapSettings().useSmartCard();

         m_pConnectionInformation->clearLog();

         SmartCardState sc;

         if (fUseSmartCard && sc.readersAvailable() <= 0)
            m_pVPNControlTask->restartPcscDaemon();

         if (!fUseSmartCard || sc.readersAvailable() > 0)
         {
            if (!fUseSmartCard || sc.waitForCardPresent() > 0)
            {
               const QString strGateway(ConnectionSettings().gateway(strConnectionName));

               delete m_pState;
               m_pState = new Connecting(m_pTrayIcon, strGateway);
               updateContextMenu(true);

               m_pVPNControlTask->setConnectionName(strConnectionName);
               m_pVPNControlTask->setAction(VPNControlTask::Connect);
               m_pVPNControlTask->start();
               m_fIsExecuting = true;
               m_pTimeout->start();
               QTimer::singleShot(PTPINTERFACE_CHECK_UP_TIME, this, SLOT(onCheckPtpInterfaceIsUp()));
            }
         }
         else
            QMessageBox::critical(NULL, qApp->applicationName(), QObject::tr("No smart card reader found."));
      }
   }

//   qDebug() << "ConnectionManager::vpnConnect(const QString&" << strConnectionName << ") -> finished";
}


void ConnectionManager::vpnConnect(QAction* pAction)
{
   if (m_pTrayIconMenu && pAction)
   {
      if (!pAction->data().isNull())
         vpnConnect(pAction->data().toString());
   }
}

void ConnectionManager::vpnDisconnect(bool fDontChangeStatus)
{
//   qDebug() << "ConnectionManager::vpnDisconnect(bool" << fDontChangeStatus << ")";

   if (!m_fIsExecuting)
   {
      if (!fDontChangeStatus)
      {
         const ConnectionSettings settings;
         const QString strGateway(settings.gateway(m_pVPNControlTask->connectionName()));

         delete m_pState;
         m_pState = new Disconnecting(m_pTrayIcon, strGateway);

         updateContextMenu(true);
      }

      m_pVPNControlTask->setAction(VPNControlTask::Disconnect);
      m_pVPNControlTask->start();
      m_fIsExecuting = true;
      m_pTimeout->start();
      QTimer::singleShot(PTPINTERFACE_CHECK_DOWN_TIME, this, SLOT(onCheckPtpInterfaceIsDown()));
   }

//   qDebug() << "ConnectionManager::vpnDisconnect(bool" << fDontChangeStatus << ") -> finished";
}

void ConnectionManager::editConnections() const
{
   m_Application.startConnectionEditorDialog();
}

void ConnectionManager::showConnectionInformation() const
{
   m_pConnectionInformation->show();

   if (!m_pConnectionInformation->isActiveWindow())
   {
      m_pConnectionInformation->activateWindow();
      m_pConnectionInformation->raise();
   }
}

void ConnectionManager::about() const
{
   QIcon logo;
   logo.addFile(QString::fromUtf8(":/images/logo"), QSize(), QIcon::Normal, QIcon::Off);

   QMessageBox about;
   about.setWindowIcon(logo);
   about.setWindowTitle(tr("About %1").arg(L2tpIPsecVpnApplication::applicationName()));
   about.setText("<big><b>" + L2tpIPsecVpnApplication::applicationName() + " " + L2tpIPsecVpnApplication::applicationVersion() + "</b></big>");
   about.setInformativeText("<p><center>" + tr("Notification area applet for managing your L2tp over IPsec virtual private network connections.") + "</center></p>" + strAbout);
   about.setStandardButtons(QMessageBox::Close);
   about.exec();
}

void ConnectionManager::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
   switch (reason)
   {
      case QSystemTrayIcon::MiddleClick:
         showMessage();
         break;

      case QSystemTrayIcon::Context:
         updateContextMenu(false);
         break;

      case QSystemTrayIcon::Trigger:
         updateContextMenu(false);
         m_pTrayIconMenu->popup(QCursor::pos());
         break;

      default:
         ;
   }
}

void ConnectionManager::showMessage()
{
   m_pTrayIcon->showMessage(m_pState->msgTitle(), m_pState->msgBody(), m_pState->msgIcon(), 5 * 1000);
}

void ConnectionManager::messageClicked()
{
   showConnectionInformation();
}

void ConnectionManager::detectConnectionState()
{
   const ConnectionInfo connectionInfo(connectionNameOfUpAndRunningPtpInterface());
   if (!connectionInfo.first.isNull())
   {
      if (NetworkInterface::writeDefaultGatewayInfo())
         connected(connectionInfo.first, connectionInfo.second);
      else
         vpnDisconnect(true);
   }
   else
      onRouteAdded(NetworkInterface::null, 0);

   NetworkInterfaceMonitor::instance()->subscribe(this);
   NetworkInterfaceMonitor::instance()->start();
}

void ConnectionManager::onVpnTaskOutput(const QString& strOutputLine)
{
//   qDebug() << "ConnectionManager::onVpnTaskOutput(const QString&" << strOutputLine << ")";

   if (strOutputLine.trimmed().length() > 0)
      m_pConnectionInformation->appendLogPlainText((strOutputLine + '\n').toAscii().constData());

//   qDebug() << "ConnectionManager::onVpnTaskOutput(const QString&" << strOutputLine << ") -> finished";
}

void ConnectionManager::onVpnTaskReadyReadLog()
{
//   qDebug() << "ConnectionManager::onVpnTaskReadyReadLog()";

   char acBuf[1024];

   qint64 iRet;
   do
   {
      iRet = m_pVPNControlTask->readLogLine(acBuf, sizeof(acBuf));
      if (iRet > 0)
         m_pConnectionInformation->appendLogPlainText(acBuf);

   } while (iRet != -1);

//   qDebug() << "ConnectionManager::onVpnTaskReadyReadLog() -> finished";
}

void ConnectionManager::onVpnTaskErrorMsg(int iErrorCode)
{
//   qDebug() << "ConnectionManager::onVpnTaskErrorMsg(int" << iErrorCode << ")";

   char acBuf[1024];

   const qint64 iLineLength = m_pVPNControlTask->readErrorLine(acBuf, sizeof(acBuf));
   if (iLineLength > 0)
   {
      m_pConnectionInformation->appendLogColorText(QColor(255, 0, 0), acBuf);
      error(iErrorCode);
   }

//   qDebug() << "ConnectionManager::onVpnTaskErrorMsg(int" << iErrorCode << ") -> finished";
}

void ConnectionManager::onVpnTaskTimeout()
{
//   qDebug() << "ConnectionManager::onVpnTaskTimeout()";

   if (m_fIsExecuting)
   {
      m_pConnectionInformation->appendLogColorText(QColor(255, 0, 0), "Last command timed out\n");

      m_fIsExecuting = !m_pVPNControlTask->stop(1000);

      if ((m_pState->isState(ConnectionState::Connecting) || m_pState->isState(ConnectionState::Disconnecting)))
         error(500);
   }

//   qDebug() << "ConnectionManager::onVpnTaskTimeout() -> finished";
}

void ConnectionManager::onVpnTaskFinished()
{
//   qDebug() << "ConnectionManager::onVpnTaskFinished()";

   m_pTimeout->stop();
   m_fIsExecuting = false;

//   qDebug() << "ConnectionManager::onVpnTaskFinished() -> finished";
}

void ConnectionManager::onConnectionAdded(const QString& strName)
{
//   qDebug() << "ConnectionManager::onConnectionAdded(const QString&" << strName << ")";

   if (m_pTrayIconMenu && m_pActions)
   {
      m_pActions->append(new QAction(strName, this));
      m_pActions->last()->setData(strName);
      m_pActions->last()->setToolTip(tr("Click to establish a vpn connection to '%1'").arg(strName));

      if (m_pState->isState(ConnectionState::NotConnected) || m_pState->isState(ConnectionState::Error))
         m_pActions->last()->setEnabled(true);
      else
         m_pActions->last()->setEnabled(false);

      m_pTrayIconMenu->insertAction(action(DISC), m_pActions->last());
   }

//   qDebug() << "ConnectionManager::onConnectionAdded(const QString&" << strName << ") -> finished";
}

void ConnectionManager::onConnectionRemoved(const QString& strName)
{
//   qDebug() << "ConnectionManager::onConnectionRemoved(const QString&" << strName << ")";

   if (m_pTrayIconMenu && m_pActions)
   {
      QAction* pAction = NULL;
      for (int i = QUIT + 1; !pAction && i < m_pActions->size(); i++)
      {
         if (m_pActions->at(i)->text() == strName)
            pAction = m_pActions->at(i);
      }

      if (pAction)
      {
         m_pTrayIconMenu->removeAction(pAction);
         m_pActions->removeAll(pAction);
         delete pAction;
      }
   }

//   qDebug() << "ConnectionManager::onConnectionRemoved(const QString&" << strName << ") -> finished";
}

void ConnectionManager::onRouteAdded(NetworkInterface interface, unsigned int iPriority)
{
//   qDebug() << "ConnectionManager::onRouteAdded(" << interface.name().c_str() << ", " << iPriority << ")";

   if (iPriority != 100)
   {
      if (!m_fRoutePriorityIsChanging)
      {
         bool fHasDefaultGateway = false;
         if (!interface.isNull())
            fHasDefaultGateway = interface.hasDefaultGateway();
         else
            fHasDefaultGateway = NetworkInterface::defaultGateway().size() == 1;

         if (m_pState && (m_pState->isState(ConnectionState::NotConnected) || m_pState->isState(ConnectionState::Error)) && fHasDefaultGateway)
         {
//               qDebug() << "ConnectionManager::onRouteAdded: found default gateway";

            ConnectionSettings settings;
            const int iConnections = settings.connections();

            bool fDone = false;
            for (int i = 0; !fDone && i < iConnections; i++)
            {
               const QString strName = settings.connection(i);
               if (settings.commonSettings(strName).autoConnect())
               {
                  fDone = true;
                  vpnConnect(strName);
               }
            }
         }
      }
      else
         m_fRoutePriorityIsChanging = false;
   }
   else
      m_fRoutePriorityIsChanging = true;

//   qDebug() << "ConnectionManager::onRouteAdded(" << interface.name().c_str() << ", " << iPriority << ") -> finished";
}

void ConnectionManager::onRouteDeleted(NetworkInterface interface, unsigned int iPriority)
{
//   qDebug() << "ConnectionManager::onRouteDeleted(" << interface.name().c_str() << ", " << iPriority << ")";

   if (iPriority != 100)
   {
      if (!m_fRoutePriorityIsChanging)
      {
         if (m_pState && m_pState->isState(ConnectionState::Connected) && interface.isDefaultGateway() && !interface.hasDefaultGateway())
            vpnDisconnect();
      }
      else
         m_fRoutePriorityIsChanging = false;
   }
   else
      m_fRoutePriorityIsChanging = true;

//   qDebug() << "ConnectionManager::onRouteDeleted(" << interface.name().c_str() << ") -> finished";
}

void ConnectionManager::onPtpInterfaceIsUpAnRunning(NetworkInterface interface)
{
//   qDebug() << "ConnectionManager::onPtpInterfaceIsUpAnRunning(" << interface.name().c_str() << ")";

   if (m_pState->isState(ConnectionState::Connecting) || m_pState->isState(ConnectionState::NotConnected))
   {
      const QString strConnectionName(ConnectionManager::connectionName(interface, 5));
      if (!strConnectionName.isNull())
         connected(strConnectionName, interface);
   }

//   qDebug() << "ConnectionManager::onPtpInterfaceIsUpAnRunning(" << interface.name().c_str() << ", " << iPriority << ") -> finished";
}

void ConnectionManager::onPtpInterfaceIsGoingDown(NetworkInterface interface)
{
//   qDebug() << "ConnectionManager::onPtpInterfaceIsGoingDown(" << interface.name().c_str() << ")";

   if ((m_pState->isState(ConnectionState::Connected) || m_pState->isState(ConnectionState::Disconnecting)))
   {
      const QString strConnectionName(ConnectionManager::connectionName(interface));
      if (!strConnectionName.isNull())
         disConnected();
   }
   if (m_pState && m_pState->isState(ConnectionState::Connected) && interface.isDefaultGateway())
      vpnDisconnect();

//   qDebug() << "ConnectionManager::onPtpInterfaceIsGoingDown(" << interface.name().c_str() << ") -> finished";
}

void ConnectionManager::onCheckPtpInterfaceIsUp()
{
   if (!m_fIsExecuting && m_pState->isState(ConnectionState::Connecting))
   {
      const ConnectionInfo connectionInfo(connectionNameOfUpAndRunningPtpInterface());
      if (connectionInfo.first.isNull())
         disConnected();
      else
         connected(connectionInfo.first, connectionInfo.second);
   }
}

void ConnectionManager::onCheckPtpInterfaceIsDown()
{
   if (!m_fIsExecuting && m_pState->isState(ConnectionState::Disconnecting))
   {
      const ConnectionInfo connectionInfo(connectionNameOfUpAndRunningPtpInterface());
      if (connectionInfo.first.isNull())
         disConnected();
      else
         connected(connectionInfo.first, connectionInfo.second);
   }
}

QAction* ConnectionManager::action(ActionType type) const
{
   return(m_pActions != NULL ? m_pActions->at(type) : NULL);
}

void ConnectionManager::enableAllConnections(bool fEnable) const
{
   for (int i = QUIT + 1; i < m_pActions->size(); i++)
      m_pActions->at(i)->setEnabled(fEnable);
}

void ConnectionManager::connected(const QString& strConnectionName, const NetworkInterface& ptpInterface)
{
   const QString strGateway(ConnectionSettings().gateway(strConnectionName));

   m_pVPNControlTask->setConnectionName(strConnectionName);

   delete m_pState;

   m_pState = new Connected(m_pTrayIcon, strGateway, ptpInterface);

   updateContextMenu(true);
}

void ConnectionManager::disConnected()
{
   delete m_pState;

   m_pState = new NotConnected(m_pTrayIcon);

   updateContextMenu(true);
}

void ConnectionManager::error(int iErrorCode)
{
   if (!m_pState->isState(ConnectionState::NotConnected))
   {
      const ConnectionSettings settings;
      const QString strGateway(settings.ipsecSettings(m_pVPNControlTask->connectionName()).gateway());
      const bool fDisconnecting(!m_pState->isState(ConnectionState::Connecting));

      delete m_pState;
      m_pState = new Error(m_pTrayIcon, strGateway, iErrorCode, fDisconnecting);
      updateContextMenu(true);

      vpnDisconnect(true);
   }
}

ConnectionManager::ConnectionInfo ConnectionManager::connectionNameOfUpAndRunningPtpInterface() const
{
   QString strConnectionName;

   NetworkInterface::InterfaceMap interfaces = NetworkInterface::pointToPointInterfaces();

   NetworkInterface::InterfaceMap::const_iterator itInterfaces = interfaces.begin();
   for (; strConnectionName.isNull() && itInterfaces != interfaces.end(); ++itInterfaces)
      strConnectionName = ConnectionManager::connectionName((*itInterfaces).second);

  return(ConnectionInfo(strConnectionName, strConnectionName.isNull() ? NetworkInterface::null : (*--itInterfaces).second));
}

QString ConnectionManager::connectionName(const NetworkInterface& interface, int iRetry)
{
   QString strConnectionName;

   const NetworkInterface::AddressEntries addressEntries(interface.addressEntries());
   NetworkInterface::AddressEntries::const_iterator addressIterator(addressEntries.begin());
   for (bool fFound = false; !fFound && addressIterator != addressEntries.end(); addressIterator++)
   {
      QFile connectionNameMap(strRuntimePath + (*addressIterator).broadcast().toString());

      for (int i = 0; !fFound && i < iRetry; i++)
      {
         if (connectionNameMap.exists())
         {
            if (connectionNameMap.open(QFile::ReadOnly))
            {
               strConnectionName = connectionNameMap.readLine();
               if (!strConnectionName.isEmpty())
                  fFound = true;

               connectionNameMap.close();
            }
         }
         else
            ::sleep(1);
      }
   }

   return(strConnectionName.trimmed());
}