swift
Loading...
Searching...
No Matches
networkutils.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2013 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#include <QAbstractSocket>
7#include <QDateTime>
8#include <QHostAddress>
9#include <QList>
10#include <QMetaEnum>
11#include <QNetworkInterface>
12#include <QNetworkReply>
13#include <QObject>
14#include <QRegularExpression>
15#include <QSignalMapper>
16#include <QStringBuilder>
17#include <QTcpSocket>
18#include <QUrl>
19#include <QUrlQuery>
20#include <QVariant>
21
22#include "config/buildconfig.h"
23#include "misc/eventloop.h"
24#include "misc/network/server.h"
25#include "misc/stringutils.h"
26
27using namespace swift::config;
28using namespace swift::misc;
29using namespace swift::misc::network;
30
31namespace swift::misc::network
32{
33 int CNetworkUtils::getTimeoutMs() { return 5000; }
34
36
38 {
39 QStringList ips;
41 for (const QHostAddress &address : allAddresses)
42 {
43 if (address.isNull())
44 {
45 continue;
46 }
47 if (address.protocol() == QAbstractSocket::IPv4Protocol)
48 {
49 const QString a = address.toString();
50 ips.append(a);
51 }
52 }
53 ips.sort();
54 return ips;
55 }
56
57 bool CNetworkUtils::canConnect(const QString &hostAddress, int port, QString &message, int timeoutMs)
58 {
59 if (timeoutMs < 0)
60 {
61 timeoutMs = getTimeoutMs();
62 } // external functions might call with -1
63 QTcpSocket socket;
64 QSignalMapper mapper;
65 QObject::connect(&socket, &QTcpSocket::connected, &mapper, qOverload<>(&QSignalMapper::map));
67 mapper.setMapping(&socket, 0);
68
69 CEventLoop eventLoop;
70 eventLoop.stopWhen(&mapper, &QSignalMapper::mappedInt);
71 socket.connectToHost(hostAddress, static_cast<quint16>(port));
72 const bool timedOut = !eventLoop.exec(timeoutMs);
73
74 if (socket.state() != QTcpSocket::ConnectedState)
75 {
76 static const QString e("Connection failed: '%1'");
77 message = timedOut ? e.arg("Timed out") : e.arg(socket.errorString());
78 return false;
79 }
80 else
81 {
82 static const QString ok("OK, connected");
83 message = ok;
84 return true;
85 }
86 }
87
88 bool CNetworkUtils::canConnect(const network::CServer &server, QString &message, int timeoutMs)
89 {
90 return CNetworkUtils::canConnect(server.getAddress(), server.getPort(), message, timeoutMs);
91 }
92
93 bool CNetworkUtils::canConnect(const QString &url, QString &message, int timeoutMs)
94 {
95 if (url.isEmpty())
96 {
97 message = QObject::tr("Missing URL", "Misc");
98 return false;
99 }
100 return canConnect(QUrl(url), message, timeoutMs);
101 }
102
103 bool CNetworkUtils::canConnect(const QUrl &url, QString &message, int timeoutMs)
104 {
105 if (!url.isValid())
106 {
107 message = QObject::tr("Invalid URL: %1", "Misc").arg(url.toString());
108 return false;
109 }
110
111 if (url.isRelative())
112 {
113 message = QObject::tr("Relative URL cannot be tested: %1", "Misc").arg(url.toString());
114 return false;
115 }
116
117 const QString host(url.host());
118 const QString scheme(url.scheme().toLower());
119 int p = url.port();
120 if (p < 0)
121 {
122 p = scheme.contains("https") ? 443 : 80;
123 }
124 return canConnect(host, p, message, timeoutMs);
125 }
126
127 bool CNetworkUtils::canConnect(const QUrl &url, int timeoutMs)
128 {
129 QString m;
130 return canConnect(url, m, timeoutMs);
131 }
132
134 {
135 QHostAddress address(candidate);
136 return (QAbstractSocket::IPv4Protocol == address.protocol());
137 }
138
140 {
141 QHostAddress address(candidate);
142 return (QAbstractSocket::IPv6Protocol == address.protocol());
143 }
144
146 {
147 bool success {};
148 int p = port.toInt(&success);
149 if (!success) return false;
150 return (p >= 1 && p <= 65535);
151 }
152
153 QString CNetworkUtils::buildUrl(const QString &protocol, const QString &server, const QString &baseUrl,
154 const QString &serviceUrl)
155 {
156 Q_ASSERT_X(protocol.length() > 3, Q_FUNC_INFO, "worng protocol");
157 Q_ASSERT_X(!server.isEmpty(), Q_FUNC_INFO, "missing server");
158 Q_ASSERT_X(!serviceUrl.isEmpty(), Q_FUNC_INFO, "missing service URL");
159
160 QString url(server);
161 if (!baseUrl.isEmpty())
162 {
163 url.append("/").append(baseUrl);
164 }
165 url.append("/").append(serviceUrl);
166 url.replace("//", "/");
167 return protocol + "://" + url;
168 }
169
170 void CNetworkUtils::setSwiftUserAgent(QNetworkRequest &request, const QString &userAgentDetails)
171 {
172 static const QString defaultUserAgent("swift/" + CBuildConfig::getVersionString());
173
174 // User-Agent is known header, we use high level setHeader not setRawHeader
175 const QVariant agent = QVariant::fromValue(
176 userAgentDetails.isEmpty() ? defaultUserAgent : defaultUserAgent + "/" + userAgentDetails);
178 }
179
180 void CNetworkUtils::addDebugFlag(QUrlQuery &qurl) { qurl.addQueryItem("XDEBUG_SESSION_START", "ECLIPSE_DBGP"); }
181
183 const QString &userAgentDetails)
184 {
185 QNetworkRequest request(url);
186 switch (type)
187 {
188 case PostUrlEncoded:
189 request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
190 break;
191 default: break;
192 }
193 CNetworkUtils::setSwiftUserAgent(request, userAgentDetails);
194 return request;
195 }
196
198 const QString &userAgentDetails)
199 {
200 QNetworkRequest req(request); // copy
201 CNetworkUtils::setSwiftUserAgent(req, userAgentDetails);
202 return req;
203 }
204
206 {
207 Q_ASSERT(nwReply);
209 return lm.isValid() ? lm.toMSecsSinceEpoch() : -1;
210 }
211
213 {
214 Q_ASSERT(nwReply);
215 const QVariant lastModifiedQv = nwReply->header(QNetworkRequest::LastModifiedHeader);
216 if (lastModifiedQv.isValid() && lastModifiedQv.canConvert<QDateTime>())
217 {
218 return lastModifiedQv.value<QDateTime>();
219 }
220 return {};
221 }
222
224 {
225 const qint64 sinceEpoch = CNetworkUtils::lastModifiedMsSinceEpoch(nwReply);
226 return sinceEpoch > 0 ? std::max(0LL, QDateTime::currentMSecsSinceEpoch() - sinceEpoch) :
228 }
229
231 {
232 if (!nwReply)
233 {
234 return -1;
235 }
236 const QVariant started = nwReply->property("started");
237 if (started.isValid() && started.canConvert<qint64>())
238 {
239 const qint64 now = QDateTime::currentMSecsSinceEpoch();
240 const auto start = started.value<qint64>();
241 return (now - start);
242 }
243 return -1;
244 }
245
247 {
248 if (!nwReply)
249 {
250 return -1;
251 }
253 if (!statusCode.isValid())
254 {
255 return -1;
256 }
257 const int status = statusCode.toInt();
258 return status;
259 }
260
262 {
263 if (!nwReply)
264 {
265 return false;
266 }
267 const int code = CNetworkUtils::getHttpStatusCode(nwReply);
268 return code == 301 || code == 302 || code == 303 || code == 307;
269 }
270
272 {
273 if (!nwReply)
274 {
275 return {};
276 }
277 const QVariant possibleRedirectUrl = nwReply->attribute(QNetworkRequest::RedirectionTargetAttribute);
278 if (!possibleRedirectUrl.isValid())
279 {
280 return {};
281 }
282 QUrl redirectUrl = possibleRedirectUrl.toUrl();
283 if (redirectUrl.isRelative())
284 {
285 redirectUrl = nwReply->url().resolved(redirectUrl);
286 }
287 return redirectUrl;
288 }
289
291 {
292 if (errorMessage.isEmpty())
293 {
294 return errorMessage;
295 }
296 QString phpError(errorMessage);
297 thread_local const QRegularExpression regEx("<[^>]*>");
298 return phpError.remove(regEx);
299 }
300
302 {
303 if (errorMessage.length() < 50)
304 {
305 return false;
306 }
307 return errorMessage.contains("xdebug", Qt::CaseInsensitive);
308 }
309
311 {
312 static const QString h("HEAD");
313 static const QString g("GET");
314 static const QString put("PUT");
315 static const QString d("DELETE");
316 static const QString post("POST");
317 static const QString c("custom");
318 static const QString u("unknown");
319
320 switch (operation)
321 {
325 case QNetworkAccessManager::PostOperation: return post;
329 default: break;
330 }
331 return u;
332 }
333} // namespace swift::misc::network
static const QString & getVersionString()
Version as QVersionNumber.
Utility class which blocks until a signal is emitted or timeout reached.
Definition eventloop.h:20
bool exec(int timeoutMs)
Begin processing events until the timeout or stop condition occurs.
Definition eventloop.h:54
void stopWhen(const T *sender, F signal)
Event loop will stop if the given signal is received.
Definition eventloop.h:34
static bool looksLikePhpErrorMessage(const QString &errorMessage)
Looks like PHP error messages.
static QNetworkRequest getSwiftNetworkRequest(const QUrl &url, RequestType type=Get, const QString &userAgentDetails={})
Our tweaked network request with swift header.
static void addDebugFlag(QUrlQuery &qurl)
Add debug flag.
static bool isValidIPv4Address(const QString &candidate)
Valid IPv4 address.
static void setSwiftUserAgent(QNetworkRequest &request, const QString &userAgentDetails={})
Set user agent for request.
static bool isValidPort(const QString &port)
Valid port.
static QDateTime lastModifiedDateTime(const QNetworkReply *nwReply)
Last modified from reply.
static qint64 lastModifiedMsSinceEpoch(const QNetworkReply *nwReply)
Last modified from reply.
static qint64 requestDuration(const QNetworkReply *nwReply)
Request duration (only works if requested by swift functions).
static QStringList getKnownLocalIpV4Addresses()
Find out my IPv4 addresses including loopback, empty if not possible.
static qint64 lastModifiedSinceNow(const QNetworkReply *nwReply)
Last modified from reply compared with now (in ms).
static QString removeHtmlPartsFromPhpErrorMessage(const QString &errorMessage)
Remove the HTML formatting from a PHP error message.
static const QString & networkOperationToString(QNetworkAccessManager::Operation operation)
Operation to string.
static bool isValidIPv6Address(const QString &candidate)
Valid IPv6 address.
static bool canConnect(const QString &hostAddress, int port, QString &message, int timeoutMs=getTimeoutMs())
Can connect?
static int getTimeoutMs()
Default for timeout.
static QUrl getHttpRedirectUrl(QNetworkReply *nwReply)
Get the redirect URL if any.
static QString buildUrl(const QString &protocol, const QString &server, const QString &baseUrl, const QString &serviceUrl)
Build / concatenate an URL.
static bool isHttpStatusRedirect(QNetworkReply *nwReply)
Is the reply an HTTP redirect?
static int getHttpStatusCode(QNetworkReply *nwReply)
Get the http status code.
static int getLongTimeoutMs()
Default for timeout (long).
Value object encapsulating information of a FSD server.
Definition server.h:28
int getPort() const
Get port.
Definition server.h:93
const QString & getAddress() const
Get address.
Definition server.h:57
Free functions in swift::misc.
void connectToHost(const QHostAddress &address, quint16 port, QIODeviceBase::OpenMode openMode)
void errorOccurred(QAbstractSocket::SocketError socketError)
QAbstractSocket::SocketState state() const const
qint64 currentMSecsSinceEpoch()
bool isValid() const const
qint64 toMSecsSinceEpoch() const const
int protocol() const const
QString errorString() const const
void append(QList< T > &&value)
QList< QHostAddress > allAddresses()
QVariant attribute(QNetworkRequest::Attribute code) const const
QVariant header(QNetworkRequest::KnownHeaders header) const const
QUrl url() const const
void setHeader(QNetworkRequest::KnownHeaders header, const QVariant &value)
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
QVariant property(const char *name) const const
QString tr(const char *sourceText, const char *disambiguation, int n)
void mappedInt(int i)
void setMapping(QObject *sender, QObject *object)
QString & append(QChar ch)
QString arg(Args &&... args) const const
bool contains(QChar ch, Qt::CaseSensitivity cs) const const
bool isEmpty() const const
qsizetype length() const const
QString & remove(QChar ch, Qt::CaseSensitivity cs)
QString & replace(QChar before, QChar after, Qt::CaseSensitivity cs)
int toInt(bool *ok, int base) const const
QString toLower() const const
void sort(Qt::CaseSensitivity cs)
CaseInsensitive
QString host(QUrl::ComponentFormattingOptions options) const const
bool isRelative() const const
bool isValid() const const
int port(int defaultPort) const const
QUrl resolved(const QUrl &relative) const const
QString scheme() const const
QString toString(QUrl::FormattingOptions options) const const
void addQueryItem(const QString &key, const QString &value)
bool canConvert() const const
QVariant fromValue(T &&value)
bool isValid() const const
int toInt(bool *ok) const const
QUrl toUrl() const const
T value() const &const