MythTV master
portchecker.cpp
Go to the documentation of this file.
1
2// 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 "mythlogging.h"
36#include "mythtimer.h"
37#include "portchecker.h"
38
39#define LOC QString("PortChecker::%1(): ").arg(__func__)
40
74bool PortChecker::checkPort(QString &host, int port, std::chrono::milliseconds timeLimit, bool linkLocalOnly)
75{
76 LOG(VB_GENERAL, LOG_DEBUG, LOC + QString("host %1 port %2 timeLimit %3 linkLocalOnly %4")
77 .arg(host).arg(port).arg(timeLimit.count()).arg(linkLocalOnly));
78 m_cancelCheck = false;
79 QHostAddress addr;
80 bool isIPAddress = addr.setAddress(host);
81 bool islinkLocal = false;
82// Windows does not need the scope on the ip address so we can skip
83// some processing
84#ifndef _WIN32
85 if (isIPAddress
86 && addr.protocol() == QAbstractSocket::IPv6Protocol
87 && addr.isInSubnet(QHostAddress::parseSubnet("fe80::/10")))
88 islinkLocal = true;
89#endif
90 if (linkLocalOnly)
91 {
92 if (islinkLocal)
93 {
94 // If we already know the scope, set it here and return
96 {
97 host = addr.toString();
98 return true;
99 }
100 }
101 else
102 {
103 return false;
104 }
105 }
106 QList<QNetworkInterface> cards = QNetworkInterface::allInterfaces();
107#ifndef _WIN32
108 QListIterator<QNetworkInterface> iCard = cards;
109#endif
111 QTcpSocket socket(this);
112 QAbstractSocket::SocketState state = QAbstractSocket::UnconnectedState;
113 int retryCount = 0;
114 QString scope;
115 bool testedAll = false;
116 while (state != QAbstractSocket::ConnectedState
117 && (timer.elapsed() < timeLimit))
118 {
119 if (state == QAbstractSocket::UnconnectedState)
120 {
121// Windows does not need the scope on the ip address so we can skip
122// some processing
123#ifndef _WIN32
124 int iCardsEnd = 0;
125 if (islinkLocal && !gCoreContext->GetScopeForAddress(addr))
126 {
127 addr.setScopeId(QString());
128 while (addr.scopeId().isEmpty() && iCardsEnd<2)
129 {
130 // search for the next available IPV6 interface.
131 if (iCard.hasNext())
132 {
133 QNetworkInterface card = iCard.next();
134 LOG(VB_GENERAL, LOG_DEBUG, QString("Trying interface %1").arg(card.name()));
135 unsigned int flags = card.flags();
136 if ((flags & QNetworkInterface::IsLoopBack)
137 || !(flags & QNetworkInterface::IsRunning))
138 continue;
139 // check that IPv6 is enabled on that interface
140 QList<QNetworkAddressEntry> addresses = card.addressEntries();
141 bool foundv6 = false;
142 for (const auto& ae : std::as_const(addresses))
143 {
144 if (ae.ip().protocol() == QAbstractSocket::IPv6Protocol)
145 {
146 foundv6 = true;
147 break;
148 }
149 }
150 if (foundv6)
151 {
152 scope = card.name();
153 addr.setScopeId(scope);
154 break;
155 }
156 }
157 else
158 {
159 // Get a new list in case a new interface
160 // has been added.
161 cards = QNetworkInterface::allInterfaces();
162 iCard = cards;
163 iCard.toFront();
164 testedAll=true;
165 iCardsEnd++;
166 }
167 }
168 }
169 if (iCardsEnd > 1)
170 {
171 LOG(VB_GENERAL, LOG_ERR, LOC + QString("There is no IPV6 compatible interface for %1")
172 .arg(host));
173 break;
174 }
175#endif
176 QString dest;
177 if (isIPAddress)
178 dest=addr.toString();
179 else
180 dest=host;
181 socket.connectToHost(dest, port);
182 retryCount=0;
183 }
184 else
185 {
186 retryCount++;
187 }
188 // This retry count of 6 means 3 seconds of waiting for
189 // connection before aborting and starting a new connection attempt.
190 if (retryCount > 6)
191 socket.abort();
193 // Check if user got impatient and canceled
194 if (m_cancelCheck)
195 break;
196 std::this_thread::sleep_for(500ms);
197 state = socket.state();
198 LOG(VB_GENERAL, LOG_DEBUG, LOC + QString("socket state %1")
199 .arg(state));
200 if (linkLocalOnly
201 && state == QAbstractSocket::UnconnectedState
202 && testedAll)
203 break;
204 }
205 if (state == QAbstractSocket::ConnectedState
206 && islinkLocal && !scope.isEmpty())
207 {
209 host = addr.toString();
210 }
211 socket.abort();
213 return (state == QAbstractSocket::ConnectedState);
214}
215
230// static method
231bool PortChecker::resolveLinkLocal(QString &host, int port, std::chrono::milliseconds timeLimit)
232{
233 PortChecker checker;
234 return checker.checkPort(host,port,timeLimit,true);
235}
236
238{
239 qApp->processEvents(QEventLoop::AllEvents, 250);
240 qApp->processEvents(QEventLoop::AllEvents, 250);
241}
242
251{
252 m_cancelCheck = true;
253}
254
255
256/* vim: set expandtab tabstop=4 shiftwidth=4: */
void SetScopeForAddress(const QHostAddress &addr)
Record the scope Id of the given IP address.
bool GetScopeForAddress(QHostAddress &addr) const
Return the cached scope Id for the given address.
A QElapsedTimer based timer to replace use of QTime as a timer.
Definition: mythtimer.h:14
std::chrono::milliseconds elapsed(void)
Returns milliseconds elapsed since last start() or restart()
Definition: mythtimer.cpp:91
@ kStartRunning
Definition: mythtimer.h:17
Small class to handle TCP port checking and finding link-local context.
Definition: portchecker.h:45
bool m_cancelCheck
Definition: portchecker.h:61
static bool resolveLinkLocal(QString &host, int port, std::chrono::milliseconds timeLimit=30s)
Convenience method to resolve link-local address.
static void processEvents(void)
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:74
void cancelPortCheck(void)
Cancel the checkPort operation currently in progress.
MythCoreContext * gCoreContext
This global variable contains the MythCoreContext instance for the app.
#define LOG(_MASK_, _LEVEL_, _QSTRING_)
Definition: mythlogging.h:39
#define LOC
Definition: portchecker.cpp:39