MythTV  master
portchecker.cpp
Go to the documentation of this file.
1 // Copyright (c) 2017 MythTV Developers <mythtv-dev@mythtv.org>
3 //
4 // This is part of MythTV (https://www.mythtv.org)
5 //
6 // This program is free software; you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation; either version 2 of the License, or
9 // (at your option) any later version.
10 //
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 //
20 // You should have received a copy of the GNU General Public License
21 // along with this program. If not, see <http://www.gnu.org/licenses/>.
22 //
24 
25 #include <QCoreApplication>
26 #include <QHostAddress>
27 #include <QTcpSocket>
28 #include <QEventLoop>
29 #include <QNetworkInterface>
30 #include <QNetworkAddressEntry>
31 
32 #include <thread>
33 
34 #include "mythcorecontext.h"
35 #include "mythtimer.h"
36 #include "portchecker.h"
37 
38 #define LOC QString("PortChecker::%1(): ").arg(__func__)
39 
73 bool PortChecker::checkPort(QString &host, int port, std::chrono::milliseconds timeLimit, bool linkLocalOnly)
74 {
75  LOG(VB_GENERAL, LOG_DEBUG, LOC + QString("host %1 port %2 timeLimit %3 linkLocalOnly %4")
76  .arg(host).arg(port).arg(timeLimit.count()).arg(linkLocalOnly));
77  m_cancelCheck = false;
78  QHostAddress addr;
79  bool isIPAddress = addr.setAddress(host);
80  bool islinkLocal = false;
81 // Windows does not need the scope on the ip address so we can skip
82 // some processing
83 #ifndef _WIN32
84  if (isIPAddress
85  && addr.protocol() == QAbstractSocket::IPv6Protocol
86  && addr.isInSubnet(QHostAddress::parseSubnet("fe80::/10")))
87  islinkLocal = true;
88 #endif
89  if (linkLocalOnly)
90  {
91  if (islinkLocal)
92  {
93  // If we already know the scope, set it here and return
95  {
96  host = addr.toString();
97  return true;
98  }
99  }
100  else
101  return false;
102  }
103  QList<QNetworkInterface> cards = QNetworkInterface::allInterfaces();
104 #ifndef _WIN32
105  QListIterator<QNetworkInterface> iCard = cards;
106 #endif
108  QTcpSocket socket(this);
109  QAbstractSocket::SocketState state = QAbstractSocket::UnconnectedState;
110  int retryCount = 0;
111  QString scope;
112  bool testedAll = false;
113  while (state != QAbstractSocket::ConnectedState
114  && (timer.elapsed() < timeLimit))
115  {
116  if (state == QAbstractSocket::UnconnectedState)
117  {
118 // Windows does not need the scope on the ip address so we can skip
119 // some processing
120 #ifndef _WIN32
121  int iCardsEnd = 0;
122  if (islinkLocal && !gCoreContext->GetScopeForAddress(addr))
123  {
124  addr.setScopeId(QString());
125  while (addr.scopeId().isEmpty() && iCardsEnd<2)
126  {
127  // search for the next available IPV6 interface.
128  if (iCard.hasNext())
129  {
130  QNetworkInterface card = iCard.next();
131  LOG(VB_GENERAL, LOG_DEBUG, QString("Trying interface %1").arg(card.name()));
132  unsigned int flags = card.flags();
133  if ((flags & QNetworkInterface::IsLoopBack)
134  || !(flags & QNetworkInterface::IsRunning))
135  continue;
136  // check that IPv6 is enabled on that interface
137  QList<QNetworkAddressEntry> addresses = card.addressEntries();
138  bool foundv6 = false;
139  for (const auto& ae : qAsConst(addresses))
140  {
141  if (ae.ip().protocol() == QAbstractSocket::IPv6Protocol)
142  {
143  foundv6 = true;
144  break;
145  }
146  }
147  if (foundv6)
148  {
149  scope = card.name();
150  addr.setScopeId(scope);
151  break;
152  }
153  }
154  else
155  {
156  // Get a new list in case a new interface
157  // has been added.
158  cards = QNetworkInterface::allInterfaces();
159  iCard = cards;
160  iCard.toFront();
161  testedAll=true;
162  iCardsEnd++;
163  }
164  }
165  }
166  if (iCardsEnd > 1)
167  {
168  LOG(VB_GENERAL, LOG_ERR, LOC + QString("There is no IPV6 compatible interface for %1")
169  .arg(host));
170  break;
171  }
172 #endif
173  QString dest;
174  if (isIPAddress)
175  dest=addr.toString();
176  else
177  dest=host;
178  socket.connectToHost(dest, port);
179  retryCount=0;
180  }
181  else
182  retryCount++;
183  // This retry count of 6 means 3 seconds of waiting for
184  // connection before aborting and starting a new connection attempt.
185  if (retryCount > 6)
186  socket.abort();
187  processEvents();
188  // Check if user got impatient and canceled
189  if (m_cancelCheck)
190  break;
191  std::this_thread::sleep_for(500ms);
192  state = socket.state();
193  LOG(VB_GENERAL, LOG_DEBUG, LOC + QString("socket state %1")
194  .arg(state));
195  if (linkLocalOnly
196  && state == QAbstractSocket::UnconnectedState
197  && testedAll)
198  break;
199  }
200  if (state == QAbstractSocket::ConnectedState
201  && islinkLocal && !scope.isEmpty())
202  {
204  host = addr.toString();
205  }
206  socket.abort();
207  processEvents();
208  return (state == QAbstractSocket::ConnectedState);
209 }
210 
225 // static method
226 bool PortChecker::resolveLinkLocal(QString &host, int port, std::chrono::milliseconds timeLimit)
227 {
228  PortChecker checker;
229  return checker.checkPort(host,port,timeLimit,true);
230 }
231 
233 {
234  qApp->processEvents(QEventLoop::AllEvents, 250);
235  qApp->processEvents(QEventLoop::AllEvents, 250);
236 }
237 
246 {
247  m_cancelCheck = true;
248 }
249 
250 
251 /* vim: set expandtab tabstop=4 shiftwidth=4: */
MythTimer::elapsed
std::chrono::milliseconds elapsed(void)
Returns milliseconds elapsed since last start() or restart()
Definition: mythtimer.cpp:91
build_compdb.dest
dest
Definition: build_compdb.py:9
PortChecker
Small class to handle TCP port checking and finding link-local context.
Definition: portchecker.h:44
MythTimer
A QElapsedTimer based timer to replace use of QTime as a timer.
Definition: mythtimer.h:13
LOG
#define LOG(_MASK_, _LEVEL_, _QSTRING_)
Definition: mythlogging.h:39
PortChecker::m_cancelCheck
bool m_cancelCheck
Definition: portchecker.h:61
MythCoreContext::GetScopeForAddress
bool GetScopeForAddress(QHostAddress &addr) const
Return the cached scope Id for the given address.
Definition: mythcorecontext.cpp:1108
portchecker.h
PortChecker::resolveLinkLocal
static bool resolveLinkLocal(QString &host, int port, std::chrono::milliseconds timeLimit=30s)
Convenience method to resolve link-local address.
Definition: portchecker.cpp:226
gCoreContext
MythCoreContext * gCoreContext
This global variable contains the MythCoreContext instance for the app.
Definition: mythcorecontext.cpp:55
PortChecker::checkPort
bool checkPort(QString &host, int port, std::chrono::milliseconds timeLimit=30s, bool linkLocalOnly=false)
Check if a port is open and sort out the link-local scope.
Definition: portchecker.cpp:73
MythTimer::kStartRunning
@ kStartRunning
Definition: mythtimer.h:17
mythcorecontext.h
mythtimer.h
MythCoreContext::SetScopeForAddress
void SetScopeForAddress(const QHostAddress &addr)
Record the scope Id of the given IP address.
Definition: mythcorecontext.cpp:1128
LOC
#define LOC
Definition: portchecker.cpp:38
PortChecker::cancelPortCheck
void cancelPortCheck(void)
Cancel the checkPort operation currently in progress.
Definition: portchecker.cpp:245
PortChecker::processEvents
static void processEvents(void)
Definition: portchecker.cpp:232