summaryrefslogtreecommitdiff
path: root/Network
diff options
context:
space:
mode:
authorChristoph Berg <myon@debian.org>2026-09-26 23:24:03 +0200
committerChristoph Berg <myon@debian.org>2026-09-26 23:24:03 +0200
commit059831534c7e884f0a607ed86b582fd00d821731 (patch)
tree76bcb67a78f8aa2654fd34c2ad801a62136b0170 /Network
parentd83a420f0517d7fc47aeb288a6a0cf4891784fcc (diff)
New upstream version 3.2.0~rc1+dfsgupstream/3.2.0_rc1+dfsg
Diffstat (limited to 'Network')
-rw-r--r--Network/Cloudlog.cpp965
-rw-r--r--Network/Cloudlog.hpp119
-rw-r--r--Network/CloudlogConfiguration.hpp16
-rw-r--r--Network/DecodedTime.cpp65
-rw-r--r--Network/DecodedTime.hpp13
-rw-r--r--Network/FileDownload.cpp8
-rw-r--r--Network/FoxVerifier.cpp3
-rw-r--r--Network/MessageClient.cpp468
-rw-r--r--Network/MessageClient.hpp15
-rw-r--r--Network/Network.pri21
-rw-r--r--Network/NetworkMessage.hpp70
-rw-r--r--Network/PSKReporter.cpp11
-rw-r--r--Network/PSKReporter.hpp2
-rw-r--r--Network/eqsl.cpp2
-rw-r--r--Network/tests/PSKReporter/PSKReporter.IESpec12
-rw-r--r--Network/tests/PSKReporter/listener.py94
-rw-r--r--Network/tests/PSKReporter/python-ipfix.patch64
-rw-r--r--Network/wsprnet.cpp699
-rw-r--r--Network/wsprnet.h137
19 files changed, 2327 insertions, 457 deletions
diff --git a/Network/Cloudlog.cpp b/Network/Cloudlog.cpp
index 50e2fdee..1ebb6eea 100644
--- a/Network/Cloudlog.cpp
+++ b/Network/Cloudlog.cpp
@@ -1,37 +1,429 @@
#include "Cloudlog.hpp"
-#include <future>
-#include <chrono>
+#include <algorithm>
+#include <array>
+#include <initializer_list>
-#include <QHash>
-#include <QString>
+#include <QApplication>
#include <QDate>
-#include <QFile>
-#include <QTextStream>
-#include <QDir>
-#include <QFileInfo>
-#include <QPointer>
-#include <QSaveFile>
-#include <QUrl>
-#include <QNetworkAccessManager>
-#include <QNetworkReply>
-#include <QDebug>
-#include <QMessageBox>
-#include <QIcon>
+#include <QHash>
+#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
+#include <QJsonValue>
+#include <QMessageBox>
+#include <QNetworkAccessManager>
+#include <QNetworkReply>
+#include <QNetworkRequest>
+#include <QPointer>
+#include <QUrl>
+#include <QVariant>
+#include <QXmlStreamReader>
#include "pimpl_impl.hpp"
#include "moc_Cloudlog.cpp"
-#include "Configuration.hpp"
#include "revision_utils.hpp"
namespace
{
- // Dictionary mapping call sign to date of last upload to LotW
- using dictionary = QHash<QString, QDate>;
+ enum class EndpointLayout
+ {
+ DirectApi,
+ IndexPhpApi
+ };
+
+ enum class AuthStatus
+ {
+ Writable,
+ ReadOnly,
+ Invalid,
+ Unavailable,
+ Unexpected
+ };
+
+ enum class ServerProduct
+ {
+ Wavelog,
+ UnknownOrOther
+ };
+
+ struct AuthResult
+ {
+ AuthResult () = default;
+ AuthResult (AuthStatus status, QString const& detail)
+ : status {status}
+ , detail {detail}
+ {
+ }
+
+ AuthStatus status {AuthStatus::Unavailable};
+ QString detail;
+ };
+
+ QString endpointPath (EndpointLayout layout, QString const& apiPath)
+ {
+ return (EndpointLayout::DirectApi == layout ? QStringLiteral ("/api/") : QStringLiteral ("/index.php/api/")) + apiPath;
+ }
+
+ QString encodedKey (QString const& apiKey)
+ {
+ return QString::fromLatin1 (QUrl::toPercentEncoding (apiKey));
+ }
+
+ QUrl endpointUrl (QString const& baseUrl, EndpointLayout layout, QString const& apiPath, QString const& apiKey)
+ {
+ return QUrl {baseUrl + endpointPath (layout, apiPath) + QLatin1Char ('/') + encodedKey (apiKey)};
+ }
+
+ QHash<QString, EndpointLayout>& uploadLayoutCache ()
+ {
+ static QHash<QString, EndpointLayout> cache;
+ return cache;
+ }
+
+ void applyCommonHeaders (QNetworkRequest& request, bool acceptJson)
+ {
+ request.setRawHeader ("User-Agent", http_user_agent ().toUtf8 ());
+ if (acceptJson)
+ {
+ request.setRawHeader ("Accept", "application/json");
+ }
+ }
+
+ QNetworkRequest jsonPostRequest (QUrl const& url)
+ {
+ QNetworkRequest request {url};
+ request.setHeader (QNetworkRequest::ContentTypeHeader, QVariant {QStringLiteral ("application/json")});
+ applyCommonHeaders (request, true);
+ return request;
+ }
+
+ QNetworkRequest connectionCheckGetRequest (QUrl const& url, bool acceptJson)
+ {
+ QNetworkRequest request {url};
+ applyCommonHeaders (request, acceptJson);
+ return request;
+ }
+
+ bool isTransportError (QNetworkReply const& reply)
+ {
+ return QNetworkReply::NoError != reply.error ()
+ && !reply.attribute (QNetworkRequest::HttpStatusCodeAttribute).isValid ();
+ }
+
+ int httpStatus (QNetworkReply const& reply)
+ {
+ return reply.attribute (QNetworkRequest::HttpStatusCodeAttribute).toInt ();
+ }
+
+ QString lowerString (QJsonObject const& object, char const * key)
+ {
+ return object.value (QLatin1String {key}).toString ().trimmed ().toLower ();
+ }
+
+ AuthResult parseJsonAuth (QByteArray const& body, int statusCode)
+ {
+ QJsonParseError error;
+ auto const document = QJsonDocument::fromJson (body, &error);
+ if (QJsonParseError::NoError != error.error || !document.isObject ())
+ {
+ return {statusCode == 401 || statusCode == 403 ? AuthStatus::Invalid : AuthStatus::Unavailable,
+ QStringLiteral ("Authentication endpoint did not return JSON.")};
+ }
+
+ auto const object = document.object ();
+ auto const status = lowerString (object, "status");
+ auto const rights = lowerString (object, "rights");
+
+ if (status == QLatin1String ("invalid") || status == QLatin1String ("failed")
+ || status == QLatin1String ("failure") || statusCode == 401 || statusCode == 403)
+ {
+ return {AuthStatus::Invalid, object.value (QStringLiteral ("message")).toString ()};
+ }
+
+ if (status != QLatin1String ("valid") && status != QLatin1String ("ok"))
+ {
+ return {AuthStatus::Unavailable, QStringLiteral ("Authentication endpoint did not report a valid status.")};
+ }
+
+ if (rights.isEmpty ())
+ {
+ return {AuthStatus::Unexpected, QStringLiteral ("Authentication succeeded but did not include API key rights.")};
+ }
+
+ if (rights.startsWith (QLatin1String ("rw")))
+ {
+ return {AuthStatus::Writable, QStringLiteral ("API key is writable.")};
+ }
+
+ if (rights.startsWith (QLatin1Char ('r')))
+ {
+ return {AuthStatus::ReadOnly, QStringLiteral ("API key is read-only.")};
+ }
+
+ return {AuthStatus::Unexpected, QStringLiteral ("Authentication returned unrecognized API key rights: %1").arg (rights)};
+ }
+
+ AuthResult parseXmlAuth (QByteArray const& body)
+ {
+ QString status;
+ QString rights;
+ QXmlStreamReader xml;
+ xml.addData (QString::fromUtf8 (body));
+ while (!xml.atEnd ())
+ {
+ xml.readNext ();
+ if (xml.isStartElement ())
+ {
+ if (xml.name () == QLatin1String ("status"))
+ {
+ status = xml.readElementText ().trimmed ().toLower ();
+ }
+ else if (xml.name () == QLatin1String ("rights"))
+ {
+ rights = xml.readElementText ().trimmed ().toLower ();
+ }
+ }
+ }
+
+ if (xml.hasError ())
+ {
+ return {AuthStatus::Unavailable, QStringLiteral ("Authentication endpoint did not return XML.")};
+ }
+
+ if (status != QLatin1String ("valid"))
+ {
+ return {AuthStatus::Invalid, QStringLiteral ("API key is invalid.")};
+ }
+
+ if (rights.isEmpty ())
+ {
+ return {AuthStatus::Unexpected, QStringLiteral ("Authentication succeeded but did not include API key rights.")};
+ }
+
+ if (rights.startsWith (QLatin1String ("rw")))
+ {
+ return {AuthStatus::Writable, QStringLiteral ("API key is writable.")};
+ }
+
+ if (rights.startsWith (QLatin1Char ('r')))
+ {
+ return {AuthStatus::ReadOnly, QStringLiteral ("API key is read-only.")};
+ }
+
+ return {AuthStatus::Unexpected, QStringLiteral ("Authentication returned unrecognized API key rights: %1").arg (rights)};
+ }
+
+ int intValue (QJsonValue const& value)
+ {
+ if (value.isDouble ())
+ {
+ return value.toInt ();
+ }
+ bool ok {false};
+ auto const result = value.toString ().toInt (&ok);
+ return ok ? result : 0;
+ }
+
+ QString stringValue (QJsonObject const& object, std::initializer_list<char const *> keys)
+ {
+ for (auto const key : keys)
+ {
+ auto const value = object.value (QLatin1String {key});
+ if (!value.isUndefined () && !value.isNull ())
+ {
+ return value.toVariant ().toString ().trimmed ();
+ }
+ }
+ return {};
+ }
+
+ bool appendStationProfile (QJsonObject const& object, QList<Cloudlog::StationProfile>& profiles)
+ {
+ auto const id = intValue (object.value (QStringLiteral ("station_id")));
+ auto const alternate_id = id ? id : intValue (object.value (QStringLiteral ("station_profile_id")));
+ auto const profile_id = alternate_id ? alternate_id : intValue (object.value (QStringLiteral ("id")));
+ if (!profile_id)
+ {
+ return false;
+ }
+
+ profiles.append ({profile_id,
+ stringValue (object, {"station_profile_name", "profile_name", "name"}),
+ stringValue (object, {"station_callsign", "callsign", "call"})});
+ return true;
+ }
+
+ void collectStationProfiles (QJsonValue const& value, QList<Cloudlog::StationProfile>& profiles)
+ {
+ if (value.isArray ())
+ {
+ auto const array = value.toArray ();
+ for (auto const& entry : array)
+ {
+ collectStationProfiles (entry, profiles);
+ }
+ return;
+ }
+
+ if (!value.isObject ())
+ {
+ return;
+ }
+
+ auto const object = value.toObject ();
+ if (appendStationProfile (object, profiles))
+ {
+ return;
+ }
+
+ for (auto const& key : {QStringLiteral ("stations"), QStringLiteral ("station_profiles"),
+ QStringLiteral ("stationProfiles"), QStringLiteral ("profiles")})
+ {
+ auto const child = object.value (key);
+ if (!child.isUndefined ())
+ {
+ collectStationProfiles (child, profiles);
+ }
+ }
+ }
+
+ QString stationProfileList (QList<Cloudlog::StationProfile> const& profiles)
+ {
+ QStringList entries;
+ for (auto const& profile : profiles)
+ {
+ entries.append (Cloudlog::stationProfileDisplayText (profile));
+ }
+ return entries.join (QStringLiteral (", "));
+ }
+
+ QString jsonDiagnostic (QJsonValue const& value)
+ {
+ if (value.isString ())
+ {
+ return value.toString ();
+ }
+ if (value.isArray ())
+ {
+ QStringList values;
+ for (auto const& entry : value.toArray ())
+ {
+ auto const text = jsonDiagnostic (entry);
+ if (!text.isEmpty ())
+ {
+ values.append (text);
+ }
+ }
+ return values.join (QStringLiteral ("; "));
+ }
+ if (value.isObject ())
+ {
+ QStringList values;
+ auto const object = value.toObject ();
+ for (auto it = object.constBegin (); it != object.constEnd (); ++it)
+ {
+ auto const text = jsonDiagnostic (it.value ());
+ if (!text.isEmpty ())
+ {
+ values.append (it.key () + QStringLiteral (": ") + text);
+ }
+ }
+ return values.join (QStringLiteral ("; "));
+ }
+ return value.toVariant ().toString ();
+ }
+
+ QString responseFailureDetail (QJsonObject const& object, QString const& fallback)
+ {
+ for (auto const& key : {QStringLiteral ("reason"), QStringLiteral ("message"), QStringLiteral ("messages")})
+ {
+ auto const detail = jsonDiagnostic (object.value (key));
+ if (!detail.isEmpty ())
+ {
+ return detail;
+ }
+ }
+ return fallback;
+ }
+
+ ServerProduct parseProductManifest (QByteArray const& body)
+ {
+ QJsonParseError error;
+ auto const document = QJsonDocument::fromJson (body, &error);
+ if (QJsonParseError::NoError != error.error || !document.isObject ())
+ {
+ return ServerProduct::UnknownOrOther;
+ }
+
+ auto const object = document.object ();
+ for (auto const& key : {QStringLiteral ("name"), QStringLiteral ("short_name")})
+ {
+ if (object.value (key).toString ().trimmed ().compare (QStringLiteral ("Wavelog"), Qt::CaseInsensitive) == 0)
+ {
+ return ServerProduct::Wavelog;
+ }
+ }
+
+ return ServerProduct::UnknownOrOther;
+ }
+
+ Cloudlog::UploadResult classifyQsoUploadReply (int httpStatusCode, QNetworkReply::NetworkError networkError,
+ QString const& errorString, QByteArray const& body)
+ {
+ if (QNetworkReply::NoError != networkError && httpStatusCode == 0)
+ {
+ return {Cloudlog::UploadStatus::NetworkError,
+ Cloudlog::tr ("QSO could not be sent to Cloudlog."),
+ errorString,
+ httpStatusCode};
+ }
+
+ QJsonParseError error;
+ auto const document = QJsonDocument::fromJson (body, &error);
+ if (QJsonParseError::NoError != error.error || !document.isObject ())
+ {
+ if (httpStatusCode >= 400)
+ {
+ return {Cloudlog::UploadStatus::HttpError,
+ Cloudlog::tr ("QSO upload was rejected by Cloudlog."),
+ Cloudlog::tr ("HTTP status %1. Response was not JSON.").arg (httpStatusCode),
+ httpStatusCode};
+ }
+ return {Cloudlog::UploadStatus::UnexpectedResponse,
+ Cloudlog::tr ("Cloudlog returned an unexpected upload response."),
+ error.errorString (),
+ httpStatusCode};
+ }
+
+ auto const object = document.object ();
+ auto const status = lowerString (object, "status");
+ if (status == QLatin1String ("failed") || status == QLatin1String ("failure") || status == QLatin1String ("invalid"))
+ {
+ auto detail = responseFailureDetail (object, {});
+ if (detail.isEmpty ())
+ {
+ detail = Cloudlog::tr ("Cloudlog reported upload status: %1").arg (status);
+ }
+ return {Cloudlog::UploadStatus::Rejected,
+ Cloudlog::tr ("QSO could not be sent to Cloudlog."),
+ detail,
+ httpStatusCode};
+ }
+
+ if (httpStatusCode >= 400)
+ {
+ auto const detail = responseFailureDetail (object, Cloudlog::tr ("HTTP status %1.").arg (httpStatusCode));
+ return {Cloudlog::UploadStatus::HttpError,
+ Cloudlog::tr ("QSO upload was rejected by Cloudlog."),
+ detail,
+ httpStatusCode};
+ }
+
+ return {Cloudlog::UploadStatus::Success, {}, {}, httpStatusCode};
+ }
}
class Cloudlog::impl final
@@ -40,138 +432,515 @@ class Cloudlog::impl final
Q_OBJECT
public:
- impl (Cloudlog * self, Configuration const * config)
+ impl (Cloudlog * self, CloudlogConfiguration const * config, QNetworkAccessManager * network_manager)
: self_ {self}
, config_ {config}
- , network_manager_ {new QNetworkAccessManager(this)}
+ , network_manager_ {network_manager}
{
}
- void logQso (QByteArray ADIF)
+ void logQso (QByteArray const& ADIF)
{
- QByteArray data;
-
- QString str = QString("") +
- "{" +
- "\"key\":\""+ config_->cloudlog_api_key() +"\"," +
- "\"station_profile_id\":\""+ QVariant(config_->cloudlog_api_station_id()).toString() +"\"," +
- "\"type\":\"adif\"," +
- "\"string\":\"" + ADIF + "<eor>" + "\"" +
- "}";
- data = str.toUtf8();
-
- QUrl u = QUrl(config_->cloudlog_api_url()+"/index.php/api/qso");
+ if (!config_)
+ {
+ return;
+ }
- QNetworkRequest request(u);
- request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
- request.setRawHeader ("User-Agent", http_user_agent ().toUtf8 ());
- reply_ = network_manager_->post(request, data);
- connect (reply_.data (), &QNetworkReply::finished, this, &Cloudlog::impl::reply_logqso);
+ auto const base_url = Cloudlog::normalizeBaseUrl (config_->cloudlog_api_url ());
+ auto const data = Cloudlog::qsoUploadPayload (config_->cloudlog_api_key (), config_->cloudlog_api_station_id (), ADIF);
+ auto const layout = uploadLayoutCache ().value (base_url, EndpointLayout::IndexPhpApi);
+ auto const path = EndpointLayout::DirectApi == layout ? QStringLiteral ("/api/qso") : QStringLiteral ("/index.php/api/qso");
+ auto const u = QUrl {base_url + path};
+ auto request = jsonPostRequest (u);
+ upload_reply_ = network_manager_->post (request, data);
+ connect (upload_reply_.data (), &QNetworkReply::finished, this, &Cloudlog::impl::reply_logqso);
}
- void testApi (QString const& url, QString const& apiKey)
+ void checkConnection (Cloudlog::ConnectionCheckRequest const& request)
{
- QString apiUrl = url.trimmed();
+ abortCheckReply ();
+ check_request_ = request;
+ check_request_.url = Cloudlog::normalizeBaseUrl (request.url);
+ auth_layout_index_ = 0;
+ dry_run_layout_index_ = 0;
+ checked_station_profiles_.clear ();
+
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
if (QNetworkAccessManager::Accessible != network_manager_->networkAccessible ())
{
- // try and recover network access for QNAM
network_manager_->setNetworkAccessible (QNetworkAccessManager::Accessible);
}
#endif
- // Remove trailing slash if given
- if (apiUrl.endsWith('/')) {
- apiUrl.chop(1);
- }
- // Remove full path to API if given
- if (apiUrl.endsWith("/index.php/api/qso")) {
- apiUrl.chop(QStringLiteral("/index.php/api/qso").size());
- }
+ if (check_request_.url.isEmpty ())
+ {
+ finish ({Cloudlog::ConnectionCheckStatus::EndpointUnavailable,
+ tr ("Enter a Cloudlog or Wavelog URL."),
+ tr ("The connection check needs a base URL before it can contact the API."),
+ check_request_.url});
+ return;
+ }
- QNetworkRequest request {apiUrl+"/index.php/api/auth/"+apiKey};
- request.setRawHeader ("User-Agent", http_user_agent ().toUtf8 ());
- request.setOriginatingObject (this);
- reply_ = network_manager_->get (request);
- connect (reply_.data (), &QNetworkReply::finished, this, &Cloudlog::impl::reply_apitest);
+ startJsonAuth ();
}
- void reply_apitest()
+private:
+ using Layouts = std::array<EndpointLayout, 2>;
+
+ void startJsonAuth ()
{
- QString result;
- if (reply_ && reply_->isFinished ())
+ static Layouts const layouts {EndpointLayout::DirectApi, EndpointLayout::IndexPhpApi};
+ if (auth_layout_index_ >= layouts.size ())
{
- result = reply_->readAll();
- if (result.contains("<status>Valid</status>"))
- {
- if (result.contains("<rights>rw</rights>"))
- {
- // fprintf(stderr, "API key OK\n");
- Q_EMIT self_->apikey_ok ();
- } else {
- // fprintf(stderr, "API key not writable!\n");
- Q_EMIT self_->apikey_ro ();
- }
- } else {
- // fprintf(stderr, "API key invalid!\n");
- Q_EMIT self_->apikey_invalid ();
- }
+ startXmlAuth ();
+ return;
}
+
+ validated_auth_layout_ = layouts[auth_layout_index_++];
+ auto request = connectionCheckGetRequest (
+ endpointUrl (check_request_.url, validated_auth_layout_, QStringLiteral ("check_auth"), check_request_.apiKey), true);
+ check_reply_ = network_manager_->get (request);
+ connect (check_reply_.data (), &QNetworkReply::finished, this, &Cloudlog::impl::reply_json_auth);
}
- void reply_logqso()
+ void reply_json_auth ()
{
- QString result;
- if (reply_ && reply_->isFinished ())
+ auto * reply = takeCheckReply ();
+ if (!reply)
{
- result = reply_->readAll();
- QJsonDocument data = QJsonDocument::fromJson(result.toUtf8());
- QJsonObject obj = data.object();
- if (obj["status"] == "failed") {
- QMessageBox msgBox;
- msgBox.setIcon(QMessageBox::Warning);
- msgBox.setWindowTitle("Cloudlog Error!");
- msgBox.setText("QSO could not be sent to Cloudlog!\nPlease check your log.");
- msgBox.setDetailedText("Reason: "+obj["reason"].toString());
- msgBox.exec();
- }
+ return;
+ }
+
+ if (isTransportError (*reply))
+ {
+ auto const detail = reply->errorString ();
+ reply->deleteLater ();
+ finishNetworkError (detail);
+ return;
}
+
+ auto const result = parseJsonAuth (reply->readAll (), httpStatus (*reply));
+ reply->deleteLater ();
+ handleAuthResult (result, [this] { startJsonAuth (); });
+ }
+
+ void startXmlAuth ()
+ {
+ validated_auth_layout_ = EndpointLayout::IndexPhpApi;
+ auto request = connectionCheckGetRequest (
+ endpointUrl (check_request_.url, validated_auth_layout_, QStringLiteral ("auth"), check_request_.apiKey), false);
+ check_reply_ = network_manager_->get (request);
+ connect (check_reply_.data (), &QNetworkReply::finished, this, &Cloudlog::impl::reply_xml_auth);
+ }
+
+ void reply_xml_auth ()
+ {
+ auto * reply = takeCheckReply ();
+ if (!reply)
+ {
+ return;
+ }
+
+ if (isTransportError (*reply))
+ {
+ auto const detail = reply->errorString ();
+ reply->deleteLater ();
+ finishNetworkError (detail);
+ return;
+ }
+
+ auto const result = parseXmlAuth (reply->readAll ());
+ reply->deleteLater ();
+ handleAuthResult (result, [this] {
+ finish ({Cloudlog::ConnectionCheckStatus::EndpointUnavailable,
+ tr ("Cloudlog or Wavelog authentication endpoint was not found."),
+ tr ("Tried /api/check_auth, /index.php/api/check_auth, and /index.php/api/auth."),
+ check_request_.url});
+ });
}
- void abort ()
+ template<typename Continue>
+ void handleAuthResult (AuthResult const& result, Continue continueProbe)
{
- if (reply_ && reply_->isRunning ())
+ switch (result.status)
+ {
+ case AuthStatus::Writable:
+ startStationInfo ();
+ break;
+ case AuthStatus::ReadOnly:
+ finish ({Cloudlog::ConnectionCheckStatus::ReadOnlyKey,
+ tr ("API key is valid but read-only."),
+ tr ("Generate a read/write API key before enabling QSO uploads."),
+ check_request_.url});
+ break;
+ case AuthStatus::Invalid:
+ finish ({Cloudlog::ConnectionCheckStatus::InvalidKey,
+ tr ("API key is invalid."),
+ result.detail,
+ check_request_.url});
+ break;
+ case AuthStatus::Unexpected:
+ finish ({Cloudlog::ConnectionCheckStatus::UnexpectedResponse,
+ tr ("Authentication response was not usable."),
+ result.detail,
+ check_request_.url});
+ break;
+ case AuthStatus::Unavailable:
+ continueProbe ();
+ break;
+ }
+ }
+
+ void startStationInfo ()
+ {
+ auto request = connectionCheckGetRequest (
+ endpointUrl (check_request_.url, validated_auth_layout_, QStringLiteral ("station_info"), check_request_.apiKey), true);
+ check_reply_ = network_manager_->get (request);
+ connect (check_reply_.data (), &QNetworkReply::finished, this, &Cloudlog::impl::reply_station_info);
+ }
+
+ void reply_station_info ()
+ {
+ auto * reply = takeCheckReply ();
+ if (!reply)
+ {
+ return;
+ }
+
+ if (isTransportError (*reply))
+ {
+ auto const detail = reply->errorString ();
+ reply->deleteLater ();
+ finishNetworkError (detail);
+ return;
+ }
+
+ QJsonParseError error;
+ auto const document = QJsonDocument::fromJson (reply->readAll (), &error);
+ reply->deleteLater ();
+ if (QJsonParseError::NoError != error.error)
{
- reply_->abort ();
+ finish ({Cloudlog::ConnectionCheckStatus::UnexpectedResponse,
+ tr ("Station profile response was not JSON."),
+ error.errorString (),
+ check_request_.url});
+ return;
+ }
+
+ QList<Cloudlog::StationProfile> profiles;
+ collectStationProfiles (document.isArray () ? QJsonValue {document.array ()} : QJsonValue {document.object ()}, profiles);
+ checked_station_profiles_ = profiles;
+ auto const match = std::find_if (profiles.cbegin (), profiles.cend (), [this] (Cloudlog::StationProfile const& profile) {
+ return profile.id == check_request_.stationId;
+ });
+
+ if (match == profiles.cend ())
+ {
+ auto const available = stationProfileList (profiles);
+ finish ({Cloudlog::ConnectionCheckStatus::StationProfileUnavailable,
+ tr ("Configured station profile was not found."),
+ available.isEmpty ()
+ ? tr ("No station profiles were returned by the server.")
+ : tr ("Available station profiles: %1").arg (available),
+ check_request_.url});
+ return;
+ }
+
+ startProductProbe ();
+ }
+
+ void startProductProbe ()
+ {
+ auto request = connectionCheckGetRequest (QUrl {check_request_.url + QStringLiteral ("/manifest.json")}, true);
+ check_reply_ = network_manager_->get (request);
+ connect (check_reply_.data (), &QNetworkReply::finished, this, &Cloudlog::impl::reply_product_probe);
+ }
+
+ void reply_product_probe ()
+ {
+ auto * reply = takeCheckReply ();
+ if (!reply)
+ {
+ return;
+ }
+
+ auto const status_code = httpStatus (*reply);
+ auto const body = reply->readAll ();
+ auto const has_transport_error = isTransportError (*reply);
+ reply->deleteLater ();
+
+ if (!has_transport_error && status_code == 200 && ServerProduct::Wavelog == parseProductManifest (body))
+ {
+ startDryRun ();
+ return;
+ }
+
+ finishWithoutDryRun ();
+ }
+
+ void startDryRun ()
+ {
+ static Layouts const layouts {EndpointLayout::DirectApi, EndpointLayout::IndexPhpApi};
+ if (dry_run_layout_index_ >= layouts.size ())
+ {
+ finish ({Cloudlog::ConnectionCheckStatus::EndpointUnavailable,
+ tr ("Wavelog dry-run QSO endpoint was not found."),
+ tr ("Tried /api/qso/true and /index.php/api/qso/true after Wavelog was identified."),
+ check_request_.url});
+ return;
+ }
+
+ validated_dry_run_layout_ = layouts[dry_run_layout_index_++];
+ auto const data = Cloudlog::qsoUploadPayload (check_request_.apiKey, check_request_.stationId, dryRunAdif ());
+ auto request = jsonPostRequest (QUrl {check_request_.url + endpointPath (validated_dry_run_layout_, QStringLiteral ("qso/true"))});
+ check_reply_ = network_manager_->post (request, data);
+ connect (check_reply_.data (), &QNetworkReply::finished, this, &Cloudlog::impl::reply_dry_run);
+ }
+
+ void reply_dry_run ()
+ {
+ auto * reply = takeCheckReply ();
+ if (!reply)
+ {
+ return;
+ }
+
+ if (isTransportError (*reply))
+ {
+ auto const detail = reply->errorString ();
+ reply->deleteLater ();
+ finishNetworkError (detail);
+ return;
+ }
+
+ auto const status_code = httpStatus (*reply);
+ auto const body = reply->readAll ();
+ reply->deleteLater ();
+ if (status_code == 404 || status_code == 405)
+ {
+ startDryRun ();
+ return;
+ }
+
+ QJsonParseError error;
+ auto const document = QJsonDocument::fromJson (body, &error);
+ if (QJsonParseError::NoError != error.error || !document.isObject ())
+ {
+ finish ({Cloudlog::ConnectionCheckStatus::UnexpectedResponse,
+ tr ("Dry-run upload response was not usable."),
+ error.errorString (),
+ check_request_.url});
+ return;
+ }
+
+ auto const object = document.object ();
+ auto const status = lowerString (object, "status");
+
+ if (status_code == 201 && status == QLatin1String ("created"))
+ {
+ uploadLayoutCache ().insert (check_request_.url, validated_dry_run_layout_);
+ finish ({Cloudlog::ConnectionCheckStatus::Success,
+ tr ("Connection check passed."),
+ tr ("Writable API key, station profile, and dry-run QSO upload were validated."),
+ check_request_.url});
+ return;
+ }
+
+ if (status_code == 400 || status_code == 401 || status_code == 403)
+ {
+ finish ({Cloudlog::ConnectionCheckStatus::UploadShapeRejected,
+ tr ("Dry-run QSO upload was rejected."),
+ responseFailureDetail (object, tr ("The QSO dry-run upload was rejected.")),
+ check_request_.url});
+ return;
+ }
+
+ finish ({Cloudlog::ConnectionCheckStatus::UnexpectedResponse,
+ tr ("Dry-run QSO upload returned an unexpected response."),
+ responseFailureDetail (object, tr ("The QSO dry-run upload was rejected.")),
+ check_request_.url});
+ }
+
+ void finishWithoutDryRun ()
+ {
+ uploadLayoutCache ().insert (check_request_.url, validated_auth_layout_);
+ finish ({Cloudlog::ConnectionCheckStatus::Success,
+ tr ("Connection check passed."),
+ tr ("Writable API key and station profile were validated. No safe dry-run QSO endpoint was identified, so no test QSO was uploaded."),
+ check_request_.url});
+ }
+
+ QByteArray dryRunAdif () const
+ {
+ auto const today = QDate::currentDate ().toString (QStringLiteral ("yyyyMMdd")).toLatin1 ();
+ return QByteArray {"<call:5>WSJTX<qso_date:8>"} + today
+ + QByteArray {"<time_on:6>000000<band:3>20m<mode:3>FT8"};
+ }
+
+ void finishNetworkError (QString const& detail)
+ {
+ finish ({Cloudlog::ConnectionCheckStatus::NetworkError,
+ tr ("Network error while checking Cloudlog or Wavelog."),
+ detail,
+ check_request_.url});
+ }
+
+ void finish (Cloudlog::ConnectionCheckResult const& result)
+ {
+ check_reply_ = nullptr;
+ auto result_with_profiles = result;
+ if (result_with_profiles.stationProfiles.isEmpty ())
+ {
+ result_with_profiles.stationProfiles = checked_station_profiles_;
+ }
+ Q_EMIT self_->connection_check_finished (result_with_profiles);
+ }
+
+ void showUploadWarning (Cloudlog::UploadResult const& result)
+ {
+ if (Cloudlog::UploadStatus::Success == result.status || !qobject_cast<QApplication *> (QCoreApplication::instance ()))
+ {
+ return;
+ }
+
+ QMessageBox msgBox;
+ msgBox.setIcon (QMessageBox::Warning);
+ msgBox.setWindowTitle (tr ("Cloudlog Error!"));
+ msgBox.setText (result.message);
+ if (!result.detail.isEmpty ())
+ {
+ msgBox.setDetailedText (tr ("Reason: %1").arg (result.detail));
+ }
+ msgBox.exec ();
+ }
+
+ void reply_logqso ()
+ {
+ auto * reply = qobject_cast<QNetworkReply *> (sender ());
+ if (!reply)
+ {
+ return;
+ }
+
+ if (reply == upload_reply_)
+ {
+ upload_reply_ = nullptr;
+ }
+
+ auto const result = classifyQsoUploadReply (httpStatus (*reply), reply->error (), reply->errorString (), reply->readAll ());
+ Q_EMIT self_->qso_upload_finished (result);
+ showUploadWarning (result);
+ reply->deleteLater ();
+ }
+
+ QNetworkReply * takeCheckReply ()
+ {
+ auto * reply = qobject_cast<QNetworkReply *> (sender ());
+ if (!reply || reply != check_reply_)
+ {
+ return nullptr;
+ }
+ check_reply_ = nullptr;
+ return reply;
+ }
+
+ void abortCheckReply ()
+ {
+ if (check_reply_)
+ {
+ auto * reply = check_reply_.data ();
+ check_reply_ = nullptr;
+ if (reply->isRunning ())
+ {
+ reply->abort ();
+ }
+ reply->deleteLater ();
}
}
Cloudlog * self_;
- Configuration const * config_;
+ CloudlogConfiguration const * config_;
QNetworkAccessManager * network_manager_;
- QPointer<QNetworkReply> reply_;
+ QPointer<QNetworkReply> upload_reply_;
+ QPointer<QNetworkReply> check_reply_;
+ Cloudlog::ConnectionCheckRequest check_request_;
+ EndpointLayout validated_auth_layout_ {EndpointLayout::IndexPhpApi};
+ EndpointLayout validated_dry_run_layout_ {EndpointLayout::IndexPhpApi};
+ std::size_t auth_layout_index_ {0};
+ std::size_t dry_run_layout_index_ {0};
+ QList<Cloudlog::StationProfile> checked_station_profiles_;
};
#include "Cloudlog.moc"
-Cloudlog::Cloudlog (Configuration const * config,
- QObject * parent)
+QString Cloudlog::normalizeBaseUrl (QString const& url)
+{
+ auto result = url.trimmed ();
+ while (result.endsWith (QLatin1Char ('/')))
+ {
+ result.chop (1);
+ }
+ for (auto const& endpoint : {QStringLiteral ("/index.php/api/qso"), QStringLiteral ("/api/qso")})
+ {
+ if (result.endsWith (endpoint))
+ {
+ result.chop (endpoint.size ());
+ break;
+ }
+ }
+ while (result.endsWith (QLatin1Char ('/')))
+ {
+ result.chop (1);
+ }
+ return result;
+}
+
+QByteArray Cloudlog::qsoUploadPayload (QString const& apiKey, qint32 stationId, QByteArray const& ADIF)
+{
+ QJsonObject object;
+ object.insert (QStringLiteral ("key"), apiKey);
+ object.insert (QStringLiteral ("station_profile_id"), QString::number (stationId));
+ object.insert (QStringLiteral ("type"), QStringLiteral ("adif"));
+ object.insert (QStringLiteral ("string"), QString::fromUtf8 (ADIF + QByteArray {"<eor>"}));
+ return QJsonDocument {object}.toJson (QJsonDocument::Compact);
+}
+
+QString Cloudlog::stationProfileDisplayText (StationProfile const& profile)
+{
+ QStringList fields {QString::number (profile.id)};
+ if (!profile.name.isEmpty ())
+ {
+ fields.append (profile.name);
+ }
+ if (!profile.callsign.isEmpty ())
+ {
+ fields.append (profile.callsign);
+ }
+ return fields.join (QStringLiteral (" - "));
+}
+
+Cloudlog::Cloudlog (CloudlogConfiguration const * config, QNetworkAccessManager * network_manager, QObject * parent)
: QObject {parent}
- , m_ {this, config}
+ , m_ {this, config, network_manager}
{
+ qRegisterMetaType<Cloudlog::ConnectionCheckResult> ("Cloudlog::ConnectionCheckResult");
+ qRegisterMetaType<Cloudlog::ConnectionCheckResult> ("ConnectionCheckResult");
+ qRegisterMetaType<Cloudlog::StationProfile> ("Cloudlog::StationProfile");
+ qRegisterMetaType<Cloudlog::UploadResult> ("Cloudlog::UploadResult");
+ qRegisterMetaType<Cloudlog::UploadResult> ("UploadResult");
}
Cloudlog::~Cloudlog ()
{
}
-void Cloudlog::testApi (QString const& url, QString const& apiKey)
+void Cloudlog::checkConnection (ConnectionCheckRequest const& request)
{
- m_->testApi (url, apiKey);
+ m_->checkConnection (request);
}
void Cloudlog::logQso (QByteArray ADIF)
{
- m_->logQso(ADIF);
+ m_->logQso (ADIF);
}
diff --git a/Network/Cloudlog.hpp b/Network/Cloudlog.hpp
index 61bb7a0e..5857a5a5 100644
--- a/Network/Cloudlog.hpp
+++ b/Network/Cloudlog.hpp
@@ -1,13 +1,15 @@
#ifndef CLOUDLOG_HPP_
#define CLOUDLOG_HPP_
-#include <boost/core/noncopyable.hpp>
+#include <QByteArray>
+#include <QList>
+#include <QMetaType>
#include <QObject>
+#include <QString>
+#include "CloudlogConfiguration.hpp"
#include "pimpl_h.hpp"
-class QString;
class QNetworkAccessManager;
-class Configuration;
//
// Cloudlog
@@ -18,19 +20,118 @@ class Cloudlog final
Q_OBJECT
public:
- explicit Cloudlog (Configuration const * config, QObject * parent = nullptr);
+ enum class ConnectionCheckStatus
+ {
+ Success,
+ ReadOnlyKey,
+ InvalidKey,
+ StationProfileUnavailable,
+ EndpointUnavailable,
+ UploadShapeRejected,
+ NetworkError,
+ UnexpectedResponse
+ };
+ Q_ENUM (ConnectionCheckStatus)
+
+ enum class UploadStatus
+ {
+ Success,
+ Rejected,
+ NetworkError,
+ HttpError,
+ UnexpectedResponse
+ };
+ Q_ENUM (UploadStatus)
+
+ struct ConnectionCheckRequest
+ {
+ ConnectionCheckRequest () = default;
+ ConnectionCheckRequest (QString const& url, QString const& apiKey, qint32 stationId)
+ : url {url}
+ , apiKey {apiKey}
+ , stationId {stationId}
+ {
+ }
+
+ QString url;
+ QString apiKey;
+ qint32 stationId {0};
+ };
+
+ struct StationProfile
+ {
+ StationProfile () = default;
+ StationProfile (int id, QString const& name, QString const& callsign)
+ : id {id}
+ , name {name}
+ , callsign {callsign}
+ {
+ }
+
+ int id {0};
+ QString name;
+ QString callsign;
+ };
+
+ struct ConnectionCheckResult
+ {
+ ConnectionCheckResult () = default;
+ ConnectionCheckResult (ConnectionCheckStatus status, QString const& message, QString const& detail,
+ QString const& normalizedBaseUrl, QList<StationProfile> const& stationProfiles = {})
+ : status {status}
+ , message {message}
+ , detail {detail}
+ , normalizedBaseUrl {normalizedBaseUrl}
+ , stationProfiles {stationProfiles}
+ {
+ }
+
+ ConnectionCheckStatus status {ConnectionCheckStatus::UnexpectedResponse};
+ QString message;
+ QString detail;
+ QString normalizedBaseUrl;
+ QList<StationProfile> stationProfiles;
+ };
+
+ struct UploadResult
+ {
+ UploadResult () = default;
+ UploadResult (UploadStatus status, QString const& message, QString const& detail, int httpStatusCode)
+ : status {status}
+ , message {message}
+ , detail {detail}
+ , httpStatusCode {httpStatusCode}
+ {
+ }
+
+ UploadStatus status {UploadStatus::UnexpectedResponse};
+ QString message;
+ QString detail;
+ int httpStatusCode {0};
+ };
+
+ explicit Cloudlog (CloudlogConfiguration const * config, QNetworkAccessManager * network_manager,
+ QObject * parent = nullptr);
~Cloudlog ();
- void logQso(QByteArray ADIF);
- Q_SLOT void testApi (QString const& url, QString const& apiKey);
+ static QString normalizeBaseUrl (QString const& url);
+ static QString stationProfileDisplayText (StationProfile const& profile);
+ static QByteArray qsoUploadPayload (QString const& apiKey, qint32 stationId, QByteArray const& ADIF);
+
+ void logQso (QByteArray ADIF);
+ Q_SLOT void checkConnection (ConnectionCheckRequest const& request);
- Q_SIGNAL void apikey_ok () const;
- Q_SIGNAL void apikey_ro () const;
- Q_SIGNAL void apikey_invalid () const;
+ Q_SIGNAL void connection_check_finished (ConnectionCheckResult const& result) const;
+ Q_SIGNAL void qso_upload_finished (UploadResult const& result) const;
private:
class impl;
pimpl<impl> m_;
};
+Q_DECLARE_METATYPE (Cloudlog::ConnectionCheckResult)
+Q_DECLARE_METATYPE (Cloudlog::StationProfile)
+Q_DECLARE_METATYPE (Cloudlog::UploadStatus)
+Q_DECLARE_METATYPE (Cloudlog::UploadResult)
+
#endif
diff --git a/Network/CloudlogConfiguration.hpp b/Network/CloudlogConfiguration.hpp
new file mode 100644
index 00000000..ff2876e3
--- /dev/null
+++ b/Network/CloudlogConfiguration.hpp
@@ -0,0 +1,16 @@
+#ifndef CLOUDLOG_CONFIGURATION_HPP_
+#define CLOUDLOG_CONFIGURATION_HPP_
+
+#include <QString>
+
+class CloudlogConfiguration
+{
+public:
+ virtual ~CloudlogConfiguration () = default;
+
+ virtual QString cloudlog_api_url () const = 0;
+ virtual QString cloudlog_api_key () const = 0;
+ virtual qint32 cloudlog_api_station_id () const = 0;
+};
+
+#endif
diff --git a/Network/DecodedTime.cpp b/Network/DecodedTime.cpp
new file mode 100644
index 00000000..79572479
--- /dev/null
+++ b/Network/DecodedTime.cpp
@@ -0,0 +1,65 @@
+#include "DecodedTime.hpp"
+
+#include <QTime>
+#include <QtMath>
+
+namespace
+{
+ constexpr int secondsPerDay {24 * 60 * 60};
+
+ bool parseTime(QString const& encodedTime, QTime& time, int& secondsSinceMidnight)
+ {
+ if (encodedTime.size() != 4 && encodedTime.size() != 6) {
+ return false;
+ }
+ for (auto const character : encodedTime) {
+ if (!character.isDigit()) {
+ return false;
+ }
+ }
+
+ bool ok = false;
+ auto const hours = encodedTime.mid(0, 2).toInt(&ok);
+ if (!ok) {
+ return false;
+ }
+ auto const minutes = encodedTime.mid(2, 2).toInt(&ok);
+ if (!ok) {
+ return false;
+ }
+ auto const seconds = encodedTime.size() == 6
+ ? encodedTime.mid(4, 2).toInt(&ok) : 0;
+ if (!ok) {
+ return false;
+ }
+
+ time = QTime {hours, minutes, seconds};
+ if (!time.isValid()) {
+ return false;
+ }
+ secondsSinceMidnight = time.hour() * 60 * 60 + time.minute() * 60 + time.second();
+ return true;
+ }
+}
+
+namespace DecodedTime
+{
+ QDateTime spotTime(QString const& encodedTime, QDateTime const& nowUtc,
+ double periodSeconds)
+ {
+ QTime time;
+ int secondsSinceMidnight {0};
+ if (!parseTime(encodedTime, time, secondsSinceMidnight) || !nowUtc.isValid()) {
+ return {};
+ }
+
+ auto const currentDate = nowUtc.toUTC().date();
+ auto const spotDate = secondsSinceMidnight + qCeil(periodSeconds) >= secondsPerDay
+ ? currentDate.addDays(-1) : currentDate;
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+ return {spotDate, time, QTimeZone::UTC};
+#else
+ return {spotDate, time, Qt::UTC};
+#endif
+ }
+}
diff --git a/Network/DecodedTime.hpp b/Network/DecodedTime.hpp
new file mode 100644
index 00000000..e06eaf45
--- /dev/null
+++ b/Network/DecodedTime.hpp
@@ -0,0 +1,13 @@
+#ifndef DECODED_TIME_HPP
+#define DECODED_TIME_HPP
+
+#include <QDateTime>
+#include <QString>
+
+namespace DecodedTime
+{
+ QDateTime spotTime (QString const& encodedTime, QDateTime const& nowUtc,
+ double periodSeconds);
+}
+
+#endif
diff --git a/Network/FileDownload.cpp b/Network/FileDownload.cpp
index 3ab2a7c6..91b9048f 100644
--- a/Network/FileDownload.cpp
+++ b/Network/FileDownload.cpp
@@ -131,6 +131,11 @@ void FileDownload::replyComplete()
void FileDownload::downloadComplete(QNetworkReply *data)
{
+ if (data != reply_)
+ {
+ return;
+ }
+
// make a temp file in the same place as the file we're downloading. Needs to be on the same
// filesystem as where we eventually want to 'mv' it.
@@ -171,7 +176,8 @@ void FileDownload::download(QUrl qurl)
LOG_INFO(QString{"FileDownload [%1]: Starting download of %2 to %3"}.arg(user_agent_).arg(source_url_).arg(destination_filename_));
- request_.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
+ request_.setAttribute(QNetworkRequest::RedirectPolicyAttribute
+ , QNetworkRequest::NoLessSafeRedirectPolicy);
request_.setRawHeader("Accept", "*/*");
request_.setRawHeader ("User-Agent", user_agent_.toLocal8Bit()); // Must have a UA for some sites, like country-files
diff --git a/Network/FoxVerifier.cpp b/Network/FoxVerifier.cpp
index 36e55442..072de2f6 100644
--- a/Network/FoxVerifier.cpp
+++ b/Network/FoxVerifier.cpp
@@ -25,7 +25,8 @@ FoxVerifier::FoxVerifier(QString user_agent, QNetworkAccessManager *manager,QStr
request_ = QNetworkRequest(q_url_);
request_.setRawHeader( "User-Agent" , user_agent.toUtf8());
request_.setRawHeader( "Accept" , "*/*" );
- request_.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
+ request_.setAttribute(QNetworkRequest::RedirectPolicyAttribute
+ , QNetworkRequest::NoLessSafeRedirectPolicy);
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
request_.setTransferTimeout(FOXVERIFIER_DEFAULT_TIMEOUT_MSEC);
diff --git a/Network/MessageClient.cpp b/Network/MessageClient.cpp
index 58ebeaa0..df095508 100644
--- a/Network/MessageClient.cpp
+++ b/Network/MessageClient.cpp
@@ -9,10 +9,12 @@
#include <QNetworkInterface>
#include <QHostInfo>
#include <QTimer>
+#include <QElapsedTimer>
#include <QQueue>
#include <QByteArray>
#include <QColor>
#include <QDebug>
+#include <QtEndian>
#include "NetworkMessage.hpp"
#include "qt_helpers.hpp"
@@ -27,6 +29,34 @@
#define TRACE_UDP(MSG)
#endif
+namespace
+{
+ int constexpr replay_interval_ms {10};
+ int constexpr replay_write_budget {10};
+ int constexpr replay_message_budget {10};
+ qint64 constexpr replay_work_budget_ms {2};
+ int constexpr decode_history_limit {5000};
+ int constexpr inhibit_message_limit {4096};
+
+ bool read_inhibit_text (QDataStream& in, QString& text, quint32 limit, bool identity)
+ {
+ quint32 length {0};
+ in >> length;
+ if (length == 0xffffffff && !identity) length = 0;
+ if (in.status () != QDataStream::Ok || length > limit
+ || length > quint64 (in.device ()->bytesAvailable ())) return false;
+ QByteArray bytes (int (length), '\0');
+ if (in.readRawData (bytes.data (), bytes.size ()) != bytes.size ()) return false;
+ text = QString::fromUtf8 (bytes);
+ if (text.toUtf8 () != bytes || (identity && text.isEmpty ())) return false;
+ for (auto character : text.toUcs4 ())
+ {
+ if (!QChar::isPrint (character) || (identity && QChar::isSpace (character))) return false;
+ }
+ return true;
+ }
+}
+
class MessageClient::impl
: public QUdpSocket
{
@@ -44,10 +74,23 @@ public:
, server_port_ {server_port}
, TTL_ {TTL}
, schema_ {2} // use 2 prior to negotiation not 1 which is broken
+ , replay_state_ {ReplayState::Idle}
, heartbeat_timer_ {new QTimer {this}}
+ , replay_timer_ {new QTimer {this}}
+ , replay_generation_ {0}
{
connect (heartbeat_timer_, &QTimer::timeout, this, &impl::heartbeat);
+ replay_timer_->setSingleShot (true);
+ replay_timer_->setTimerType (Qt::PreciseTimer);
+ connect (replay_timer_, &QTimer::timeout, this, &impl::drain_replay);
connect (this, &QIODevice::readyRead, this, &impl::pending_datagrams);
+ inhibit_invalid_timer_.setParent (this);
+ inhibit_invalid_timer_.setSingleShot (true);
+ connect (&inhibit_invalid_timer_, &QTimer::timeout, this, [this] {
+ auto const count = inhibit_invalid_count_;
+ inhibit_invalid_count_ = 0;
+ Q_EMIT self_->tx_inhibit_invalid (count);
+ });
heartbeat_timer_->start (NetworkMessage::pulse * 1000);
}
@@ -62,16 +105,76 @@ public:
}
enum StreamStatus {Fail, Short, OK};
+ enum class ReplayState {Idle, Collecting, Draining};
+
+ struct PendingMessage
+ {
+ explicit PendingMessage (QByteArray const& contents)
+ : contents {contents}
+ , next_interface {0}
+ {
+ }
+
+ QByteArray contents;
+ std::size_t next_interface;
+ };
+
+ struct InhibitStatusSnapshot
+ {
+ bool valid {false};
+ bool supported {false};
+ bool inhibited {false};
+ QString source_station;
+ quint32 hold_rx {0};
+ quint32 release_rx {0};
+ quint32 expiries {0};
+ quint32 invalid {0};
+ };
+
+ struct DecodeIdentity
+ {
+ QTime time;
+ qint32 snr;
+ float delta_time;
+ quint32 delta_frequency;
+ QByteArray mode;
+ QByteArray message;
+ bool low_confidence;
+
+ bool operator== (DecodeIdentity const& other) const
+ {
+ return time == other.time && snr == other.snr && delta_time == other.delta_time
+ && delta_frequency == other.delta_frequency && mode == other.mode
+ && message == other.message && low_confidence == other.low_confidence;
+ }
+ };
void set_server (QString const& server_name, QStringList const& network_interface_names);
Q_SLOT void host_info_results (QHostInfo);
void start ();
void parse_message (QByteArray const&);
+ bool parse_tx_inhibit (QByteArray const&);
+ void invalid_inhibit ();
void pending_datagrams ();
void heartbeat ();
void closedown ();
+ bool inhibit_available () const;
+ void set_enabled (bool);
+ void update_inhibit_status (bool supported, bool inhibited,
+ QString const& source_station,
+ quint32 hold_rx, quint32 release_rx,
+ quint32 expiries, quint32 invalid);
+ void send_inhibit_status (bool supported);
+ bool begin_replay ();
+ void end_replay ();
+ void cancel_replay ();
+ void drain_replay ();
StreamStatus check_status (QDataStream const&) const;
void send_message (QByteArray const&, bool queue_if_pending = true, bool allow_duplicates = false);
+ void send_message_immediately (QByteArray const&);
+ void remember_decode (DecodeIdentity const&);
+ bool is_prior_decode (DecodeIdentity const&) const;
+ void clear_decode_history ();
void send_message (QDataStream const& out, QByteArray const& message, bool queue_if_pending = true, bool allow_duplicates = false)
{
if (OK == check_status (out))
@@ -86,6 +189,8 @@ public:
MessageClient * self_;
bool enabled_;
+ QTimer inhibit_invalid_timer_;
+ quint64 inhibit_invalid_count_ {0};
QString id_;
QString version_;
QString revision_;
@@ -95,18 +200,30 @@ public:
int TTL_;
std::vector<QNetworkInterface> network_interfaces_;
quint32 schema_;
+ ReplayState replay_state_;
QTimer * heartbeat_timer_;
+ QTimer * replay_timer_;
+ quint64 replay_generation_;
std::vector<QHostAddress> blocked_addresses_;
// hold messages sent before host lookup completes asynchronously
QQueue<QByteArray> pending_messages_;
+ QQueue<PendingMessage> replay_messages_;
+ QQueue<DecodeIdentity> decode_history_;
QByteArray last_message_;
+ InhibitStatusSnapshot inhibit_status_;
};
#include "MessageClient.moc"
void MessageClient::impl::set_server (QString const& server_name, QStringList const& network_interface_names)
{
+ cancel_replay ();
+ if (dns_lookup_id_ != -1)
+ {
+ QHostInfo::abortHostLookup (dns_lookup_id_);
+ dns_lookup_id_ = -1;
+ }
// qDebug () << "MessageClient server:" << server_name << "port:" << server_port_ << "interfaces:" << network_interface_names;
server_.setAddress (server_name);
network_interfaces_.clear ();
@@ -176,7 +293,7 @@ void MessageClient::impl::start ()
TRACE_UDP ("Trying server:" << server_.toString ());
QHostAddress interface_addr {IPv6Protocol == server_.protocol () ? QHostAddress::AnyIPv6 : QHostAddress::AnyIPv4};
- if (localAddress () != interface_addr)
+ if (state () != BoundState || localAddress () != interface_addr)
{
if (UnconnectedState != state () || state ())
{
@@ -184,7 +301,10 @@ void MessageClient::impl::start ()
}
// bind to an ephemeral port on the selected interface and set
// up for sending datagrams
- bind (interface_addr);
+ if (!bind (interface_addr))
+ {
+ return;
+ }
// qDebug () << "Bound to UDP port:" << localPort () << "on:" << localAddress ();
// set multicast TTL to limit scope when sending to multicast
@@ -204,7 +324,8 @@ void MessageClient::impl::start ()
void MessageClient::impl::pending_datagrams ()
{
- while (hasPendingDatagrams ())
+ int budget {64};
+ while (budget-- && hasPendingDatagrams ())
{
QByteArray datagram;
datagram.resize (pendingDatagramSize ());
@@ -216,10 +337,65 @@ void MessageClient::impl::pending_datagrams ()
parse_message (datagram);
}
}
+ if (hasPendingDatagrams ()) QTimer::singleShot (0, this, &impl::pending_datagrams);
+}
+
+void MessageClient::impl::invalid_inhibit ()
+{
+ ++inhibit_invalid_count_;
+ if (!inhibit_invalid_timer_.isActive ()) inhibit_invalid_timer_.start (100);
+}
+
+bool MessageClient::impl::parse_tx_inhibit (QByteArray const& msg)
+{
+ if (msg.size () < 12
+ || qFromBigEndian<quint32> (reinterpret_cast<uchar const *> (msg.constData () + 8))
+ != NetworkMessage::TxInhibit) return false;
+ if (!enabled_) return true;
+ // Bound the envelope before Reader allocates its variable-length instance ID.
+ if (msg.size () < 16 || msg.size () > inhibit_message_limit
+ || qFromBigEndian<quint32> (reinterpret_cast<uchar const *> (msg.constData () + 12)) > 1024
+ || qFromBigEndian<quint32> (reinterpret_cast<uchar const *> (msg.constData ())) != NetworkMessage::Builder::magic)
+ {
+ invalid_inhibit ();
+ return true;
+ }
+ try
+ {
+ NetworkMessage::Reader in {msg};
+ if (in.status () != QDataStream::Ok || in.schema () < 2)
+ {
+ invalid_inhibit ();
+ return true;
+ }
+ auto const id_length = qFromBigEndian<quint32> (reinterpret_cast<uchar const *> (msg.constData () + 12));
+ if (in.id ().toUtf8 () != msg.mid (16, int (id_length)))
+ {
+ invalid_inhibit ();
+ return true;
+ }
+ if (in.id () != id_) return true;
+ QString controller;
+ QString station;
+ quint32 ttl {0};
+ bool valid = read_inhibit_text (in, controller, 128, true);
+ in >> ttl;
+ valid = valid && in.status () == QDataStream::Ok
+ && (!ttl || (ttl >= 100 && ttl <= 30000))
+ && read_inhibit_text (in, station, 128, false);
+ if (!valid) invalid_inhibit ();
+ else Q_EMIT self_->tx_inhibit_command (controller, ttl, station);
+ }
+ catch (std::exception const&)
+ {
+ invalid_inhibit ();
+ }
+ return true;
}
void MessageClient::impl::parse_message (QByteArray const& msg)
{
+ if (parse_tx_inhibit (msg)) return;
try
{
//
@@ -267,9 +443,19 @@ void MessageClient::impl::parse_message (QByteArray const& msg)
<< modifiers);
if (check_status (in) != Fail)
{
- Q_EMIT self_->reply (time, snr, delta_time, delta_frequency
- , QString::fromUtf8 (mode), QString::fromUtf8 (message)
- , low_confidence, modifiers);
+ DecodeIdentity const decode {time, snr, delta_time, delta_frequency,
+ mode, message, low_confidence};
+ if (is_prior_decode (decode))
+ {
+ Q_EMIT self_->reply (time, snr, delta_time, delta_frequency
+ , QString::fromUtf8 (mode), QString::fromUtf8 (message)
+ , low_confidence, modifiers);
+ }
+ else
+ {
+ qDebug () << "process reply message ignored, decode not found:"
+ << time << snr << delta_time << delta_frequency << mode << message;
+ }
}
}
break;
@@ -281,6 +467,10 @@ void MessageClient::impl::parse_message (QByteArray const& msg)
TRACE_UDP ("Clear window:" << window);
if (check_status (in) != Fail)
{
+ if (window == 0 || window == 2)
+ {
+ clear_decode_history ();
+ }
Q_EMIT self_->clear_decodes (window);
}
}
@@ -299,7 +489,6 @@ void MessageClient::impl::parse_message (QByteArray const& msg)
TRACE_UDP ("Replay");
if (check_status (in) != Fail)
{
- last_message_.clear ();
Q_EMIT self_->replay ();
}
break;
@@ -436,6 +625,25 @@ void MessageClient::impl::parse_message (QByteArray const& msg)
}
}
+void MessageClient::impl::remember_decode (DecodeIdentity const& decode)
+{
+ if (decode_history_.size () >= decode_history_limit)
+ {
+ decode_history_.dequeue ();
+ }
+ decode_history_.enqueue (decode);
+}
+
+bool MessageClient::impl::is_prior_decode (DecodeIdentity const& decode) const
+{
+ return decode_history_.contains (decode);
+}
+
+void MessageClient::impl::clear_decode_history ()
+{
+ decode_history_.clear ();
+}
+
void MessageClient::impl::heartbeat ()
{
if (server_port_ && !server_.isNull ())
@@ -446,11 +654,70 @@ void MessageClient::impl::heartbeat ()
<< version_.toUtf8 () << revision_.toUtf8 ();
TRACE_UDP ("schema:" << schema_ << "max schema:" << NetworkMessage::Builder::schema_number << "version:" << version_ << "revision:" << revision_);
send_message (out, message, false, true);
+ if (inhibit_available ()) send_inhibit_status (true);
}
}
+bool MessageClient::impl::inhibit_available () const
+{
+ return enabled_ && inhibit_status_.valid && inhibit_status_.supported;
+}
+
+void MessageClient::impl::set_enabled (bool enabled)
+{
+ if (enabled_ == enabled) return;
+
+ auto const was_available = inhibit_available ();
+ enabled_ = enabled;
+ if (inhibit_available ())
+ {
+ send_inhibit_status (true);
+ }
+ else if (was_available)
+ {
+ send_inhibit_status (false);
+ }
+}
+
+void MessageClient::impl::update_inhibit_status (
+ bool supported, bool inhibited, QString const& source_station,
+ quint32 hold_rx, quint32 release_rx, quint32 expiries, quint32 invalid)
+{
+ auto const was_available = inhibit_available ();
+ inhibit_status_ = {
+ true, supported, inhibited, source_station,
+ hold_rx, release_rx, expiries, invalid
+ };
+ if (inhibit_available ())
+ {
+ send_inhibit_status (true);
+ }
+ else if (was_available)
+ {
+ send_inhibit_status (false);
+ }
+}
+
+void MessageClient::impl::send_inhibit_status (bool supported)
+{
+ if (!inhibit_status_.valid || !server_port_ || server_.isNull ()) return;
+
+ QByteArray message;
+ NetworkMessage::Builder out {&message, NetworkMessage::InhibitStatus,
+ id_, schema_};
+ out << supported << inhibit_status_.inhibited
+ << inhibit_status_.source_station.toUtf8 ()
+ << inhibit_status_.hold_rx << inhibit_status_.release_rx
+ << inhibit_status_.expiries << inhibit_status_.invalid;
+ TRACE_UDP ("supported:" << supported
+ << "inhibited:" << inhibit_status_.inhibited
+ << "source:" << inhibit_status_.source_station);
+ send_message (out, message, false, true);
+}
+
void MessageClient::impl::closedown ()
{
+ cancel_replay ();
if (server_port_ && !server_.isNull ())
{
QByteArray message;
@@ -460,30 +727,137 @@ void MessageClient::impl::closedown ()
}
}
+bool MessageClient::impl::begin_replay ()
+{
+ if (ReplayState::Idle != replay_state_)
+ {
+ return false;
+ }
+
+ last_message_.clear ();
+ replay_state_ = ReplayState::Collecting;
+ return true;
+}
+
+void MessageClient::impl::end_replay ()
+{
+ if (ReplayState::Collecting != replay_state_)
+ {
+ return;
+ }
+
+ if (replay_messages_.isEmpty ())
+ {
+ replay_state_ = ReplayState::Idle;
+ return;
+ }
+
+ replay_state_ = ReplayState::Draining;
+ replay_timer_->start (replay_interval_ms);
+}
+
+void MessageClient::impl::cancel_replay ()
+{
+ ++replay_generation_;
+ replay_timer_->stop ();
+ replay_messages_.clear ();
+ replay_state_ = ReplayState::Idle;
+}
+
+void MessageClient::impl::drain_replay ()
+{
+ if (ReplayState::Draining != replay_state_)
+ {
+ return;
+ }
+
+ auto const generation = replay_generation_;
+ QElapsedTimer work_timer;
+ work_timer.start ();
+ int writes {0};
+ int messages {0};
+
+ while (!replay_messages_.isEmpty ()
+ && writes < replay_write_budget
+ && messages < replay_message_budget
+ && work_timer.elapsed () < replay_work_budget_ms)
+ {
+ auto const contents = replay_messages_.head ().contents;
+ if (is_multicast_address (server_))
+ {
+ auto const next_interface = replay_messages_.head ().next_interface;
+ if (next_interface < network_interfaces_.size ())
+ {
+ if (generation != replay_generation_ || ReplayState::Draining != replay_state_)
+ {
+ return;
+ }
+ setMulticastInterface (network_interfaces_[next_interface]);
+ writeDatagram (contents, server_, server_port_);
+ if (generation != replay_generation_ || ReplayState::Draining != replay_state_)
+ {
+ return;
+ }
+ ++replay_messages_.head ().next_interface;
+ ++writes;
+ }
+
+ if (replay_messages_.head ().next_interface < network_interfaces_.size ())
+ {
+ continue;
+ }
+ }
+ else
+ {
+ if (generation != replay_generation_ || ReplayState::Draining != replay_state_)
+ {
+ return;
+ }
+ writeDatagram (contents, server_, server_port_);
+ if (generation != replay_generation_ || ReplayState::Draining != replay_state_)
+ {
+ return;
+ }
+ ++writes;
+ }
+
+ last_message_ = contents;
+ replay_messages_.dequeue ();
+ ++messages;
+ }
+
+ if (replay_messages_.isEmpty ())
+ {
+ replay_state_ = ReplayState::Idle;
+ }
+ else
+ {
+ replay_timer_->start (replay_interval_ms);
+ }
+
+ if (messages)
+ {
+ Q_EMIT self_->replay_batch_processed (messages);
+ }
+}
+
void MessageClient::impl::send_message (QByteArray const& message, bool queue_if_pending, bool allow_duplicates)
{
if (server_port_)
{
if (!server_.isNull ())
{
- if (allow_duplicates || message != last_message_) // avoid duplicates
+ auto const& previous_message = replay_messages_.isEmpty () ? last_message_ : replay_messages_.back ().contents;
+ if (allow_duplicates || message != previous_message) // avoid duplicates
{
- if (is_multicast_address (server_))
+ if (ReplayState::Idle != replay_state_)
{
- // send datagram on each selected network interface
- std::for_each (network_interfaces_.begin (), network_interfaces_.end ()
- , [&] (QNetworkInterface const& net_if) {
- setMulticastInterface (net_if);
- // qDebug () << "Multicast UDP datagram sent to:" << server_ << "port:" << server_port_ << "on:" << multicastInterface ().humanReadableName ();
- writeDatagram (message, server_, server_port_);
- });
+ replay_messages_.enqueue (PendingMessage {message});
}
else
{
- // qDebug () << "Unicast UDP datagram sent to:" << server_ << "port:" << server_port_;
- writeDatagram (message, server_, server_port_);
+ send_message_immediately (message);
}
- last_message_ = message;
}
}
else if (queue_if_pending)
@@ -493,6 +867,23 @@ void MessageClient::impl::send_message (QByteArray const& message, bool queue_if
}
}
+void MessageClient::impl::send_message_immediately (QByteArray const& message)
+{
+ if (is_multicast_address (server_))
+ {
+ for (auto const& net_if : network_interfaces_)
+ {
+ setMulticastInterface (net_if);
+ writeDatagram (message, server_, server_port_);
+ }
+ }
+ else
+ {
+ writeDatagram (message, server_, server_port_);
+ }
+ last_message_ = message;
+}
+
auto MessageClient::impl::check_status (QDataStream const& stream) const -> StreamStatus
{
auto stat = stream.status ();
@@ -546,6 +937,8 @@ MessageClient::MessageClient (QString const& id, QString const& version, QString
m_->set_server (server_name, network_interface_names);
}
+MessageClient::~MessageClient () = default;
+
QHostAddress MessageClient::server_address () const
{
return m_->server_;
@@ -563,7 +956,12 @@ void MessageClient::set_server (QString const& server_name, QStringList const& n
void MessageClient::set_server_port (port_type server_port)
{
- m_->server_port_ = server_port;
+ if (m_->server_port_ != server_port)
+ {
+ m_->cancel_replay ();
+ m_->server_port_ = server_port;
+ if (m_->dns_lookup_id_ == -1 && !m_->server_.isNull ()) m_->start ();
+ }
}
void MessageClient::set_TTL (int TTL)
@@ -574,7 +972,17 @@ void MessageClient::set_TTL (int TTL)
void MessageClient::enable (bool flag)
{
- m_->enabled_ = flag;
+ m_->set_enabled (flag);
+}
+
+bool MessageClient::begin_replay ()
+{
+ return m_->begin_replay ();
+}
+
+void MessageClient::end_replay ()
+{
+ m_->end_replay ();
}
void MessageClient::status_update (Frequency f, QString const& mode, QString const& dx_call
@@ -608,15 +1016,28 @@ void MessageClient::decode (bool is_new, QTime time, qint32 snr, float delta_tim
{
if (m_->server_port_ && !m_->server_.isNull ())
{
+ auto const mode_utf8 = mode.toUtf8 ();
+ auto const message_utf8 = message_text.toUtf8 ();
+ m_->remember_decode ({time, snr, delta_time, delta_frequency, mode_utf8,
+ message_utf8, low_confidence});
QByteArray message;
NetworkMessage::Builder out {&message, NetworkMessage::Decode, m_->id_, m_->schema_};
- out << is_new << time << snr << delta_time << delta_frequency << mode.toUtf8 ()
- << message_text.toUtf8 () << low_confidence << off_air;
+ out << is_new << time << snr << delta_time << delta_frequency << mode_utf8
+ << message_utf8 << low_confidence << off_air;
TRACE_UDP ("new" << is_new << "time:" << time << "snr:" << snr << "dt:" << delta_time << "df:" << delta_frequency << "mode:" << mode << "text:" << message_text << "low conf:" << low_confidence << "off air:" << off_air);
m_->send_message (out, message);
}
}
+void MessageClient::inhibit_status (bool supported, bool inhibited,
+ QString const& source_station,
+ quint32 hold_rx, quint32 release_rx,
+ quint32 expiries, quint32 invalid)
+{
+ m_->update_inhibit_status (supported, inhibited, source_station,
+ hold_rx, release_rx, expiries, invalid);
+}
+
void MessageClient::WSPR_decode (bool is_new, QTime time, qint32 snr, float delta_time, Frequency frequency
, qint32 drift, QString const& callsign, QString const& grid, qint32 power
, bool off_air)
@@ -634,6 +1055,7 @@ void MessageClient::WSPR_decode (bool is_new, QTime time, qint32 snr, float delt
void MessageClient::decodes_cleared ()
{
+ m_->clear_decode_history ();
if (m_->server_port_ && !m_->server_.isNull ())
{
QByteArray message;
diff --git a/Network/MessageClient.hpp b/Network/MessageClient.hpp
index 436f0203..c191b312 100644
--- a/Network/MessageClient.hpp
+++ b/Network/MessageClient.hpp
@@ -38,6 +38,7 @@ public:
QString const& server_name, port_type server_port,
QStringList const& network_interface_names,
int TTL, QObject * parent = nullptr);
+ ~MessageClient () override;
// query server details
QHostAddress server_address () const;
@@ -57,6 +58,13 @@ public:
// enable incoming messages
Q_SLOT void enable (bool);
+ Q_SIGNAL void tx_inhibit_command (QString const& controller, quint32 ttl_ms, QString const& station);
+ Q_SIGNAL void tx_inhibit_invalid (quint64 count);
+
+ // bracket serialization of a paced replay transaction
+ bool begin_replay ();
+ void end_replay ();
+
// outgoing messages
Q_SLOT void status_update (Frequency, QString const& mode, QString const& dx_call, QString const& report
, QString const& tx_mode, bool tx_enabled, bool transmitting, bool decoding
@@ -84,6 +92,10 @@ public:
// ADIF_record argument should be valid ADIF excluding any <EOR> end
// of record marker
Q_SLOT void logged_ADIF (QByteArray const& ADIF_record);
+ Q_SLOT void inhibit_status (bool supported, bool inhibited,
+ QString const& source_station,
+ quint32 hold_rx, quint32 release_rx,
+ quint32 expiries, quint32 invalid);
// this signal is emitted if the server has requested a decode
// window clear action
@@ -102,6 +114,9 @@ public:
// all decodes
Q_SIGNAL void replay ();
+ // this signal is emitted after a paced replay batch has been processed
+ Q_SIGNAL void replay_batch_processed (int message_count);
+
// this signal is emitted if the server has requested immediate (or
// auto Tx if auto_only is true) transmission to halt
Q_SIGNAL void halt_tx (bool auto_only);
diff --git a/Network/Network.pri b/Network/Network.pri
deleted file mode 100644
index 723001e9..00000000
--- a/Network/Network.pri
+++ /dev/null
@@ -1,21 +0,0 @@
-SOURCES += \
-Network/FileDownload.cpp \
-Network/FoxVerifier.cpp \
-Network/LotWUsers.cpp \
-Network/MessageClient.cpp \
-Network/NetworkAccessManager.cpp \
-Network/NetworkMessage.cpp \
-Network/NetworkServerLookup.cpp \
-Network/PSKReporter.cpp \
-Network/wsprnet.cpp
-
-HEADERS += \
-Network/FileDownload.hpp \
-Network/FoxVerifier.hpp \
-Network/LotWUsers.hpp \
-Network/MessageClient.hpp \
-Network/NetworkAccessManager.hpp \
-Network/NetworkMessage.hpp \
-Network/NetworkServerLookup.hpp \
-Network/PSKReporter.hpp \
-Network/wsprnet.h
diff --git a/Network/NetworkMessage.hpp b/Network/NetworkMessage.hpp
index 74a268fa..fdb5cb91 100644
--- a/Network/NetworkMessage.hpp
+++ b/Network/NetworkMessage.hpp
@@ -50,6 +50,10 @@
* strings and null strings. Empty strings have a length of zero
* whereas null strings have a length field of 0xffffffff.
*
+ * Reference servers distinguish clients by sender address and Id and echo
+ * that Id in requests. The destination UDP endpoint selects the WSJT-X
+ * recipient; Id is not an authorization check.
+ *
*
* Schema Negotiation
* ------------------
@@ -231,6 +235,9 @@
* validation. Off air decodes are those that result from playing
* back a .WAV file.
*
+ * Mode is the decoded-line marker ("~" for FT8, "+" for FT4), not
+ * the operating mode name carried by Status.
+ *
*
* Clear Out/In 3 quint32
* Id (unique key) utf8
@@ -279,6 +286,10 @@
* initiation the rest of the QSO is carried out manually using
* the normal WSJT-X user interface.
*
+ * Copy the fields from Time through Low confidence unchanged from
+ * Decode. Substituting a Status mode name such as "FT8" for the
+ * decoded-line marker "~" prevents matching.
+ *
* The Modifiers field allows the equivalent of keyboard
* modifiers to be sent "as if" those modifier keys where pressed
* while double-clicking the specified decoded message. The
@@ -529,6 +540,59 @@
* ffffffff will remove the sort-order value from the internal table.
* Callsigns without a sort order will be valued at zero for sorting purposes
* in the hound display.
+ *
+ * InhibitStatus Out 17
+ * Id (unique key) utf8
+ * Supported bool
+ * Inhibited bool
+ * Source station utf8
+ * Hold rx quint32
+ * Release rx quint32
+ * Expiries quint32
+ * Invalid quint32
+ *
+ * Supported means the active transceiver uses DTR or RTS PTT and Accept
+ * UDP requests is enabled, so the instance can apply inhibit commands.
+ * A supported snapshot is sent on state changes and after each Heartbeat.
+ * A final unsupported snapshot withdraws availability; controllers should
+ * expire an advertisement after three missing Heartbeat intervals.
+ * Inhibited means at least one hold is active and may remain true in a
+ * withdrawal until existing leases expire. Source station summarizes
+ * active holders. Counters are cumulative for the current transceiver
+ * lifetime.
+ *
+ * TxInhibit In 18
+ * Id (target unique key) utf8
+ * Controller ID utf8
+ * TTL milliseconds quint32
+ * Station utf8
+ *
+ * Send commands to the source address and ephemeral source port learned
+ * from ordinary WSJT-X traffic, using its exact Id and schema (2 or 3).
+ * Refresh the endpoint on subsequent traffic. Multicast allows multiple
+ * observers; unicast requires the controller to receive or relay the stream.
+ *
+ * Accept UDP requests authorizes this command. DTR or RTS PTT is required
+ * to apply holds. Disabling requests does not clear existing holds; they
+ * remain active until their leases expire.
+ *
+ * Controller ID is a stable, nonempty UTF-8 identity of at most 128 bytes,
+ * with no whitespace or nonprinting characters. Station is descriptive
+ * UTF-8 text of at most 128 bytes, without nonprinting characters; send an
+ * empty or null string when no label is needed. Both fields must be present.
+ *
+ * A zero TTL releases only this controller. A positive TTL from 100 through
+ * 30000 milliseconds creates or refreshes its hold. All unexpired holds
+ * combine with logical OR. Controller identity, not source port or Station,
+ * owns a hold. Id is required to match exactly.
+ *
+ * Up to 64 controllers are tracked individually. Additional identities
+ * extend an aggregate hold until its longest lease expires; releases
+ * cannot clear that aggregate. Its expiry counts as one expiry.
+ *
+ * Datagrams are limited to 4096 bytes and the target Id to 1024 bytes.
+ * Malformed commands are ignored and counted; other target IDs are ignored.
+ * Unknown trailing fields within the datagram limit are ignored as usual.
*/
#include <QDataStream>
@@ -561,10 +625,16 @@ namespace NetworkMessage
SwitchConfiguration,
Configure,
AnnotationInfo,
+ InhibitStatus = 17,
+ TxInhibit = 18,
maximum_message_type_ // ONLY add new message types
// immediately before here
};
+ static_assert (InhibitStatus == 17, "TX-inhibit protocol type must remain 17");
+
+ static_assert (TxInhibit == 18, "TX-inhibit command type must remain 18");
+
quint32 constexpr pulse {15}; // seconds
//
diff --git a/Network/PSKReporter.cpp b/Network/PSKReporter.cpp
index 5a0eac26..b91713ee 100644
--- a/Network/PSKReporter.cpp
+++ b/Network/PSKReporter.cpp
@@ -32,10 +32,6 @@
namespace
{
- QLatin1String HOST {"report.pskreporter.info"};
- // QLatin1String HOST {"127.0.0.1"};
- quint16 SERVICE_PORT {4739};
- // quint16 SERVICE_PORT {14739};
int MIN_SEND_INTERVAL {120}; // in seconds
int FLUSH_INTERVAL {MIN_SEND_INTERVAL + 5}; // in send intervals
int MAX_PENDING_SPOTS {2048};
@@ -162,8 +158,11 @@ public:
// use this for pseudo connection with UDP, allows us to use
// QIODevice::write() instead of QUDPSocket::writeDatagram()
- socket_->connectToHost (HOST, SERVICE_PORT, QAbstractSocket::WriteOnly);
- LOG_LOG_LOCATION (logger_, debug, "remote host: " << HOST.latin1 () << " port: " << SERVICE_PORT);
+ socket_->connectToHost (options_.destination_host, options_.destination_port,
+ QAbstractSocket::WriteOnly);
+ LOG_LOG_LOCATION (logger_, debug,
+ "remote host: " << qPrintable (options_.destination_host)
+ << " port: " << options_.destination_port);
if (!report_timer_.isActive ())
{
diff --git a/Network/PSKReporter.hpp b/Network/PSKReporter.hpp
index 46fe0a82..3b1f4f13 100644
--- a/Network/PSKReporter.hpp
+++ b/Network/PSKReporter.hpp
@@ -21,6 +21,8 @@ public:
bool use_tcpip;
QString eclipse_file_path;
QString program_info;
+ QString destination_host {"report.pskreporter.info"};
+ quint16 destination_port {4739};
};
explicit PSKReporter (Configuration const *, QString const& program_info);
diff --git a/Network/eqsl.cpp b/Network/eqsl.cpp
index 0f8b15df..5abcdadb 100644
--- a/Network/eqsl.cpp
+++ b/Network/eqsl.cpp
@@ -15,7 +15,7 @@
namespace
{
- char const * const EqslUrl = "http://www.eqsl.cc/qslcard/importADIF.cfm";
+ char const * const EqslUrl = "https://www.eqsl.cc/qslcard/importADIF.cfm";
// char const * const wsprNetUrl = "http://127.0.0.1/post?";
};
diff --git a/Network/tests/PSKReporter/PSKReporter.IESpec b/Network/tests/PSKReporter/PSKReporter.IESpec
deleted file mode 100644
index 8e95ffd0..00000000
--- a/Network/tests/PSKReporter/PSKReporter.IESpec
+++ /dev/null
@@ -1,12 +0,0 @@
-senderCallsign(30351/1)<string>[65535]
-receiverCallsign(30351/2)<string>[65535]
-senderLocator(30351/3)<string>[65535]
-receiverLocator(30351/4)<string>[65535]
-frequency(30351/5)<unsigned32>[4]
-sNR(30351/6)<signed8>[1]
-iMD(30351/7)<signed8>[1]
-decoderSoftware(30351/8)<string>[65535]
-antennaInformation(30351/9)<string>[65535]
-mode(30351/10)<string>[65535]
-informationSource(30351/11)<signed8>[1]
-persistentIdentifier(30351/12)<string>[65535]
diff --git a/Network/tests/PSKReporter/listener.py b/Network/tests/PSKReporter/listener.py
deleted file mode 100644
index 4cc0e29c..00000000
--- a/Network/tests/PSKReporter/listener.py
+++ /dev/null
@@ -1,94 +0,0 @@
-from __future__ import unicode_literals
-import sys
-import argparse
-import logging
-import time
-import threading
-import ipfix.ie
-import ipfix.reader
-import ipfix.message
-import socketserver
-import socket
-
-class IPFixDatagramHandler (socketserver.DatagramRequestHandler):
-
- def handle (self):
- logging.info (f'Connection from {self.client_address}')
- try:
- self.server.msg_buffer.from_bytes (self.packet)
- for rec in self.server.msg_buffer.namedict_iterator ():
- logging.info (f't: {self.server.msg_buffer.get_export_time()}: {rec}')
- except:
- logging.error ('Unexpected exception:', sys.exc_info ()[0])
-
-
-class IPFixUdpServer (socketserver.UDPServer):
-
- def __init__ (self, *args, **kwargs):
-
- self.msg_buffer = ipfix.message.MessageBuffer ()
- super ().__init__ (*args, **kwargs)
-
-class IPFixStreamHandler (socketserver.StreamRequestHandler):
-
- def handle (self):
- logging.info (f'Connection from {self.client_address}')
- try:
- msg_reader = ipfix.reader.from_stream (self.rfile)
- for rec in msg_reader.namedict_iterator ():
- logging.info (f't: {msg_reader.msg.get_export_time()}: {rec}')
- logging.info (f'{self.client_address} closed their connection')
- except ConnectionResetError:
- logging.info (f'{self.client_address} connection reset')
- except TimeoutError:
- logging.info (f'{self.client_address} connection timed out')
- except:
- logging.error ('Unexpected exception:', sys.exc_info ()[0])
-
-
-if __name__ == "__main__":
- INTERFACE, PORT = '', 4739
-
- ap = argparse.ArgumentParser (description='Dump IPFIX data collected over UDP')
- ap.add_argument ('-l', '--log', metavar='loglevel', default='WARNING', help='logging level')
- ap.add_argument ('-s', '--spec', metavar='specfile', help='iespec file to read')
- args = ap.parse_args ()
-
- log_level = getattr (logging, args.log.upper (), None)
- if not isinstance (log_level, int):
- raise ValueError (f'Invalif log level: {log_level}')
- logging.basicConfig (
- level=log_level
- , format='[%(levelname)s] (%(threadName)-10s) %(message)s'
- ,
- )
-
- logging.info (f'Starting IPFix servers on service port: {PORT}')
-
- ipfix.ie.use_iana_default ()
- ipfix.ie.use_5103_default ()
- if args.spec:
- ipfix.ie.use_specfile (args.spec)
-
- udp_server = IPFixUdpServer ((INTERFACE, PORT), IPFixDatagramHandler)
- udp_thread = threading.Thread (name='UDP Server', target=udp_server.serve_forever)
-
- tcp_server = socketserver.TCPServer ((INTERFACE, PORT), IPFixStreamHandler)
- tcp_server.allow_reuse_address = True
- tcp_server.socket.setsockopt (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
- tcp_thread = threading.Thread (name='TCP/IP Server', target=tcp_server.serve_forever)
-
- udp_thread.start ()
- tcp_thread.start ()
-
- try:
- while True:
- time.sleep (1000)
- except KeyboardInterrupt:
- logging.warning ('Closing down servers')
- udp_server.shutdown ()
- tcp_server.shutdown ()
-
- udp_thread.join ()
- tcp_thread.join ()
- logging.info ('Servers closed')
diff --git a/Network/tests/PSKReporter/python-ipfix.patch b/Network/tests/PSKReporter/python-ipfix.patch
deleted file mode 100644
index cb679709..00000000
--- a/Network/tests/PSKReporter/python-ipfix.patch
+++ /dev/null
@@ -1,64 +0,0 @@
-The following changes since commit e487dfbead9965c1a251d110dc55039a7ba4afef:
-
- sphinx doc update (2017-09-20 16:07:22 +0200)
-
-are available in the Git repository at:
-
- git@github.com:g4wjs/python-ipfix.git varlen-and-padding
-
-for you to fetch changes up to 6dcc106f22d25ac21b27f8ccb9b82be12e7eb18e:
-
- Parse and emit data elements correctly when variable length items included (2020-06-19 19:53:33 +0100)
-
-----------------------------------------------------------------
-Bill Somerville (2):
- Allow for alignment padding when parsing sets
- Parse and emit data elements correctly when variable length items included
-
- ipfix/message.py | 3 ++-
- ipfix/template.py | 4 ++--
- 2 files changed, 4 insertions(+), 3 deletions(-)
-
-diff --git a/ipfix/message.py b/ipfix/message.py
-index 0af2fad..71c1328 100644
---- a/ipfix/message.py
-+++ b/ipfix/message.py
-@@ -398,7 +398,7 @@ class MessageBuffer(object):
- offset += _sethdr_st.size # skip set header in decode
- if setid == template.TEMPLATE_SET_ID or\
- setid == template.OPTIONS_SET_ID:
-- while offset < setend:
-+ while offset + 4 < setend: # allow for padding up to 4 byte alignment
- (tmpl, offset) = template.decode_template_from(
- self.mbuf, offset, setid)
- # FIXME handle withdrawal
-@@ -431,6 +431,7 @@ class MessageBuffer(object):
- # KeyError on template lookup - unknown data set
- self.unknown_data_set_hook(self,
- self.mbuf[offset-_sethdr_st.size:setend])
-+ offset = setend # real end may be greater that accumulated offset
-
- def namedict_iterator(self):
- """
-diff --git a/ipfix/template.py b/ipfix/template.py
-index 1203e55..26cd8c1 100644
---- a/ipfix/template.py
-+++ b/ipfix/template.py
-@@ -187,7 +187,7 @@ class Template(object):
- offset += packplan.st.size
-
- # short circuit on no varlen
-- if not self.varlenslice:
-+ if self.varlenslice is None:
- return (vals, offset)
-
- # direct iteration over remaining IEs
-@@ -239,7 +239,7 @@ class Template(object):
- offset += packplan.st.size
-
- # shortcircuit no varlen
-- if not self.varlenslice:
-+ if self.varlenslice is None:
- return offset
-
- # direct iteration over remaining IEs
diff --git a/Network/wsprnet.cpp b/Network/wsprnet.cpp
index 14dce13d..a785acd7 100644
--- a/Network/wsprnet.cpp
+++ b/Network/wsprnet.cpp
@@ -5,6 +5,7 @@
#include "wsprnet.h"
#include <cmath>
+#include <limits>
#include <QTimer>
#include <QFile>
@@ -15,12 +16,45 @@
#include <QNetworkReply>
#include <QUrl>
#include <QDebug>
+#include <QtGlobal>
+#include <QCryptographicHash>
+
+#if QT_VERSION >= QT_VERSION_CHECK (5, 10, 0)
+#include <QRandomGenerator>
+#endif
#include "moc_wsprnet.cpp"
namespace
{
+ class QNetworkAccessManagerTransport final
+ : public QObject
+ , public WSPRNet::Transport
+ {
+ public:
+ explicit QNetworkAccessManagerTransport (QObject *parent = nullptr)
+ : QObject {parent}
+ , network_manager_ {new QNetworkAccessManager {this}}
+ {
+ }
+
+ QNetworkReply *post (QNetworkRequest const& request, QByteArray const& body) override
+ {
+#if QT_VERSION < QT_VERSION_CHECK (5, 15, 0)
+ if (QNetworkAccessManager::Accessible != network_manager_->networkAccessible ()) {
+ // try and recover network access for QNAM
+ network_manager_->setNetworkAccessible (QNetworkAccessManager::Accessible);
+ }
+#endif
+ return network_manager_->post (request, body);
+ }
+
+ private:
+ QNetworkAccessManager * network_manager_;
+ };
+
char const * const wsprNetUrl = "http://wsprnet.org/post/";
+ char const * const wsprNetUrl2 = "http://wsprnet.eu:3000/post/";
//char const * const wsprNetUrl = "http://127.0.0.1:5000/post/";
//
@@ -62,151 +96,566 @@ with app.test_request_context ():
};
WSPRNet::WSPRNet(QObject *parent)
+ : WSPRNet {nullptr, RetryPolicy {}, false, parent}
+{
+}
+
+WSPRNet::WSPRNet (Transport *transport, RetryPolicy retry_policy,
+ bool take_transport_ownership, QObject *parent)
: QObject {parent}
- , network_manager_ {new QNetworkAccessManager(this)}
- , spots_to_send_ {0}
+ , transport_ {transport ? transport : new QNetworkAccessManagerTransport {this}}
+ , owns_transport_ {transport && take_transport_ownership}
+ , retry_policy_ {retry_policy}
+ , TR_period_ {0.F}
+ , uploads_started_ {0}
+ , next_file_batch_id_ {1}
+ , next_logical_upload_id_ {1}
+ , upload_session_active_ {false}
{
+ upload_timer_.setSingleShot (true);
connect (&upload_timer_, &QTimer::timeout, this, &WSPRNet::work);
}
+WSPRNet::~WSPRNet ()
+{
+ if (owns_transport_)
+ {
+ delete transport_;
+ }
+}
+
void WSPRNet::upload (QString const& call, QString const& grid, QString const& rfreq, QString const& tfreq,
QString const& mode, float TR_period, QString const& tpct, QString const& dbm,
QString const& version, QString const& fileName)
{
- m_call = call;
- m_grid = grid;
- m_rfreq = rfreq;
- m_tfreq = tfreq;
- m_mode = mode;
- TR_period_ = TR_period;
- m_tpct = tpct;
- m_dbm = dbm;
- m_vers = version;
- m_file = fileName;
-
- // Open the wsprd.out file
- if (m_uploadType != 3)
- {
- QFile wsprdOutFile (fileName);
- if (!wsprdOutFile.open (QIODevice::ReadOnly | QIODevice::Text) || !wsprdOutFile.size ())
- {
- spot_queue_.enqueue (urlEncodeNoSpot ());
- m_uploadType = 1;
- }
- else
+ StationContext context {call, grid, rfreq, tfreq, mode, TR_period, tpct, dbm, version};
+ queueWsprFile (context, fileName);
+ flush (context);
+}
+
+void WSPRNet::queueWsprFile (StationContext const& context, QString const& file_name)
+{
+ applyContext (context);
+ auto const snapshot = snapshotFile (file_name);
+ auto const file_batch_id = beginFileBatch (snapshot);
+
+ QFile wsprdOutFile (file_name);
+ if (!wsprdOutFile.open (QIODevice::ReadOnly | QIODevice::Text) || !wsprdOutFile.size ())
+ {
+ enqueueUpload (urlEncodeNoSpot (), UploadSource::File, PayloadKind::Status, file_name, file_batch_id);
+ }
+ else
+ {
+ while (!wsprdOutFile.atEnd())
{
- // Read the contents
- while (!wsprdOutFile.atEnd())
+ SpotQueue::value_type query;
+ if (decodeLine (wsprdOutFile.readLine(), query))
{
- SpotQueue::value_type query;
- if (decodeLine (wsprdOutFile.readLine(), query))
+ // Prevent reporting data ouside of the current frequency band
+ float f = fabs (m_rfreq.toFloat() - query.queryItemValue ("tqrg", QUrl::FullyDecoded).toFloat());
+ if (f < 0.01) // MHz
{
- // Prevent reporting data ouside of the current frequency band
- float f = fabs (m_rfreq.toFloat() - query.queryItemValue ("tqrg", QUrl::FullyDecoded).toFloat());
- if (f < 0.01) // MHz
- {
- spot_queue_.enqueue(urlEncodeSpot (query));
- m_uploadType = 2;
- }
+ enqueueUpload (urlEncodeSpot (query), UploadSource::File, PayloadKind::Spot, file_name, file_batch_id);
}
}
}
}
- spots_to_send_ = spot_queue_.size ();
- upload_timer_.start (200);
+ if (file_uploads_.value (file_batch_id).total == 0)
+ {
+ file_uploads_.remove (file_batch_id);
+ }
}
void WSPRNet::post (QString const& call, QString const& grid, QString const& rfreq, QString const& tfreq,
QString const& mode, float TR_period, QString const& tpct, QString const& dbm,
QString const& version, QString const& decode_text)
{
- m_call = call;
- m_grid = grid;
- m_rfreq = rfreq;
- m_tfreq = tfreq;
- m_mode = mode;
- TR_period_ = TR_period;
- m_tpct = tpct;
- m_dbm = dbm;
- m_vers = version;
+ StationContext context {call, grid, rfreq, tfreq, mode, TR_period, tpct, dbm, version};
if (!decode_text.size ())
{
- if (!spot_queue_.size ())
+ flush (context);
+ }
+ else
+ {
+ queueFst4wDecode (context, decode_text);
+ }
+}
+
+void WSPRNet::queueFst4wDecode (StationContext const& context, QString const& decode_text)
+{
+ applyContext (context);
+ auto const& match = fst4_re.match (decode_text);
+ if (match.hasMatch ())
+ {
+ SpotQueue::value_type query;
+ auto tqrg = match.captured ("freq").toInt ();
+ query.addQueryItem ("function", "wspr");
+ // FST4W reports are intentionally not constrained to WSPR sub-bands.
+ auto const& date = QDateTime::currentDateTimeUtc ().addSecs (-context.TR_period * 3. / 4.).date ();
+ query.addQueryItem ("date", date.toString ("yyMMdd"));
+ query.addQueryItem ("time", match.captured ("time"));
+ query.addQueryItem ("sig", match.captured ("db"));
+ query.addQueryItem ("dt", match.captured ("dt"));
+ query.addQueryItem ("tqrg", QString::number (context.rfreq.toDouble () + (tqrg - 1500) / 1e6, 'f', 6));
+ query.addQueryItem ("tcall", match.captured ("call"));
+ query.addQueryItem ("drift", "0");
+ query.addQueryItem ("tgrid", match.captured ("grid"));
+ query.addQueryItem ("dbm", match.captured ("dBm"));
+ enqueueUpload (urlEncodeSpot (query), UploadSource::Direct, PayloadKind::Spot);
+ }
+}
+
+void WSPRNet::flush (StationContext const& context)
+{
+ applyContext (context);
+ if (pending_primary_uploads_.isEmpty () && !hasOutstanding (UploadTarget::Primary))
+ {
+ enqueueUpload (urlEncodeNoSpot (), UploadSource::Direct, PayloadKind::Status);
+ }
+ startUploadSession ();
+}
+
+void WSPRNet::applyContext (StationContext const& context)
+{
+ m_call = context.call;
+ m_grid = context.grid;
+ m_rfreq = context.rfreq;
+ m_tfreq = context.tfreq;
+ m_mode = context.mode;
+ TR_period_ = context.TR_period;
+ m_tpct = context.tpct;
+ m_dbm = context.dbm;
+ m_vers = context.version;
+}
+
+auto WSPRNet::snapshotFile (QString const& file_name) const -> FileSnapshot
+{
+ FileSnapshot snapshot;
+ snapshot.path = file_name;
+
+ QFile file {file_name};
+ if (!file.open (QIODevice::ReadOnly))
+ {
+ return snapshot;
+ }
+
+ auto const contents = file.readAll ();
+ snapshot.size = contents.size ();
+ snapshot.hash = QCryptographicHash::hash (contents, QCryptographicHash::Sha256);
+ return snapshot;
+}
+
+bool WSPRNet::fileMatchesSnapshot (FileSnapshot const& snapshot) const
+{
+ if (snapshot.path.isEmpty () || snapshot.size < 0)
+ {
+ return false;
+ }
+
+ QFile file {snapshot.path};
+ if (!file.open (QIODevice::ReadOnly))
+ {
+ return false;
+ }
+
+ auto const contents = file.readAll ();
+ if (contents.size () != snapshot.size)
+ {
+ return false;
+ }
+
+ return QCryptographicHash::hash (contents, QCryptographicHash::Sha256) == snapshot.hash;
+}
+
+bool WSPRNet::hasPendingFileLeg (int file_batch_id, int logical_upload_id) const
+{
+ auto is_file_leg = [file_batch_id, logical_upload_id](PendingUpload const& upload)
+ {
+ return UploadSource::File == upload.source
+ && upload.file_batch_id == file_batch_id
+ && upload.logical_upload_id == logical_upload_id;
+ };
+
+ for (auto const& upload : pending_primary_uploads_)
+ {
+ if (is_file_leg (upload))
{
- spot_queue_.enqueue (urlEncodeNoSpot ());
- m_uploadType = 3;
+ return true;
}
}
- else
+ for (auto const& upload : pending_alternate_uploads_)
{
- auto const& match = fst4_re.match (decode_text);
- if (match.hasMatch ())
+ if (is_file_leg (upload))
{
- SpotQueue::value_type query;
- // Prevent reporting data ouside of the current frequency
- // band - removed by G4WJS to accommodate FST4W spots
- // outside of WSPR segments
- auto tqrg = match.captured ("freq").toInt ();
- // if (tqrg >= 1400 && tqrg <= 1600)
- {
- query.addQueryItem ("function", "wspr");
- // use time as at 3/4 of T/R period before current to
- // ensure date is in Rx period
- auto const& date = QDateTime::currentDateTimeUtc ().addSecs (-TR_period * 3. / 4.).date ();
- query.addQueryItem ("date", date.toString ("yyMMdd"));
- query.addQueryItem ("time", match.captured ("time"));
- query.addQueryItem ("sig", match.captured ("db"));
- query.addQueryItem ("dt", match.captured ("dt"));
- query.addQueryItem ("tqrg", QString::number (rfreq.toDouble () + (tqrg - 1500) / 1e6, 'f', 6));
- query.addQueryItem ("tcall", match.captured ("call"));
- query.addQueryItem ("drift", "0");
- query.addQueryItem ("tgrid", match.captured ("grid"));
- query.addQueryItem ("dbm", match.captured ("dBm"));
- spot_queue_.enqueue (urlEncodeSpot (query));
- m_uploadType = 2;
- }
+ return true;
+ }
+ }
+ for (auto const& upload : outstanding_requests_)
+ {
+ if (is_file_leg (upload))
+ {
+ return true;
+ }
+ }
+ return false;
+}
+
+bool WSPRNet::hasOutstanding (UploadTarget target) const
+{
+ for (auto const& upload : outstanding_requests_)
+ {
+ if (upload.target == target)
+ {
+ return true;
}
}
+ return false;
}
void WSPRNet::networkReply (QNetworkReply * reply)
{
- // check if request was ours
- if (m_outstandingRequests.removeOne (reply))
+ if (!outstanding_requests_.contains (reply))
{
+ reply->deleteLater ();
+ return;
+ }
+
+ auto upload = outstanding_requests_.take (reply);
+ QString server_response;
+ if (replyAccepted (upload, reply, server_response))
+ {
+ markAccepted (upload);
+ }
+ else
+ {
+ auto const now = QDateTime::currentDateTimeUtc ();
if (QNetworkReply::NoError != reply->error ())
{
- Q_EMIT uploadStatus (QString {"Error: %1"}.arg (reply->error ()));
- // not clearing queue or halting queuing as it may be a
- // transient one off request error
+ Q_EMIT uploadStatus (QString {"Error: %1"}.arg (reply->errorString ()));
+ }
+ else
+ {
+ Q_EMIT uploadStatus (QString {"Upload Failed: %1"}.arg (server_response));
+ }
+
+ auto const retry_delay_ms = retryDelayMs (upload);
+ if (canRetry (upload, now, retry_delay_ms))
+ {
+ retryUpload (upload, now, retry_delay_ms);
}
else
{
- QString serverResponse = reply->readAll ();
- if (m_uploadType == 2)
+ markFailed (upload);
+ }
+ }
+
+ qDebug () << QString {"WSPRnet.org %1 outstanding requests"}.arg (outstanding_requests_.size ());
+
+ // delete request object instance on return to the event loop otherwise it is leaked
+ reply->deleteLater ();
+ scheduleWork ();
+ maybeFinalize ();
+}
+
+void WSPRNet::enqueueUpload (QUrlQuery const& query, UploadSource source, PayloadKind kind, QString const& source_file, int file_batch_id)
+{
+ auto const now = QDateTime::currentDateTimeUtc ();
+ auto const logical_upload_id = UploadSource::File == source ? next_logical_upload_id_++ : 0;
+ if (UploadSource::File == source)
+ {
+ auto& state = file_uploads_[file_batch_id];
+ ++state.total;
+ }
+ auto enqueue_for_target = [this, &query, source, kind, &source_file, file_batch_id,
+ logical_upload_id, now](UploadTarget target)
+ {
+ auto& uploads = target == UploadTarget::Primary
+ ? pending_primary_uploads_ : pending_alternate_uploads_;
+ uploads.enqueue ({query, source, kind, source_file, file_batch_id, now,
+ now.addMSecs (retry_policy_.ttl_ms), now, 0, target,
+ logical_upload_id});
+ };
+
+ enqueue_for_target (UploadTarget::Primary);
+ if (PayloadKind::Spot == kind
+ && !query.queryItemValue ("tgrid", QUrl::FullyDecoded).isEmpty ())
+ {
+ enqueue_for_target (UploadTarget::Alternate);
+ }
+ pruneExpiredUploads (now);
+ enforcePendingLimit ();
+}
+
+int WSPRNet::beginFileBatch (FileSnapshot const& snapshot)
+{
+ auto const file_batch_id = next_file_batch_id_++;
+ auto& state = file_uploads_[file_batch_id];
+ state.snapshot = snapshot;
+ return file_batch_id;
+}
+
+void WSPRNet::startUploadSession ()
+{
+ upload_session_active_ = true;
+ uploads_started_ = outstanding_requests_.size ();
+ scheduleWork ();
+ maybeFinalize ();
+}
+
+void WSPRNet::scheduleWork ()
+{
+ if (!upload_session_active_)
+ {
+ return;
+ }
+
+ auto const now = QDateTime::currentDateTimeUtc ();
+ pruneExpiredUploads (now);
+ QDateTime next_attempt_at;
+ auto have_next_attempt = false;
+ auto consider_queue = [this, &next_attempt_at, &have_next_attempt]
+ (QQueue<PendingUpload> const& uploads, UploadTarget target)
+ {
+ if (hasOutstanding (target))
+ {
+ return;
+ }
+ for (auto const& upload : uploads)
+ {
+ if (!have_next_attempt || upload.next_attempt_at < next_attempt_at)
+ {
+ next_attempt_at = upload.next_attempt_at;
+ have_next_attempt = true;
+ }
+ }
+ };
+ consider_queue (pending_primary_uploads_, UploadTarget::Primary);
+ consider_queue (pending_alternate_uploads_, UploadTarget::Alternate);
+ if (!have_next_attempt)
+ {
+ upload_timer_.stop ();
+ return;
+ }
+
+ auto const delay = qMax<qint64> (0, now.msecsTo (next_attempt_at));
+ upload_timer_.start (static_cast<int> (qMin<qint64> (delay, std::numeric_limits<int>::max ())));
+}
+
+void WSPRNet::pruneExpiredUploads (QDateTime const& now)
+{
+ int dropped = 0;
+ auto prune_queue = [this, &now, &dropped](QQueue<PendingUpload>& uploads)
+ {
+ for (int i = 0; i < uploads.size ();)
+ {
+ if (uploads[i].expires_at <= now)
{
- if (!serverResponse.contains(QRegExp("spot\\(s\\) added")))
- {
- Q_EMIT uploadStatus (QString {"Upload Failed: %1"}.arg (serverResponse));
- spot_queue_.clear ();
- upload_timer_.stop ();
- }
+ markFailed (uploads.takeAt (i));
+ ++dropped;
+ }
+ else
+ {
+ ++i;
}
+ }
+ };
+ prune_queue (pending_primary_uploads_);
+ prune_queue (pending_alternate_uploads_);
+ if (dropped)
+ {
+ Q_EMIT uploadStatus (QString {"Dropped %1 expired WSPRNet upload(s)"}.arg (dropped));
+ }
+}
+
+void WSPRNet::enforcePendingLimit ()
+{
+ auto const max_pending = qMax (1, retry_policy_.max_pending);
+ auto const now = QDateTime::currentDateTimeUtc ();
+ pruneExpiredUploads (now);
+
+ int dropped = 0;
+ auto enforce_queue_limit = [this, max_pending, &dropped](QQueue<PendingUpload>& uploads)
+ {
+ while (uploads.size () > max_pending)
+ {
+ markFailed (uploads.dequeue ());
+ ++dropped;
+ }
+ };
+ enforce_queue_limit (pending_primary_uploads_);
+ enforce_queue_limit (pending_alternate_uploads_);
+ if (dropped)
+ {
+ Q_EMIT uploadStatus (QString {"Dropped %1 oldest pending WSPRNet upload(s)"}.arg (dropped));
+ }
+}
+
+void WSPRNet::sendUpload (PendingUpload upload)
+{
+ auto const url = upload.target == UploadTarget::Primary ? wsprNetUrl : wsprNetUrl2;
+ QNetworkRequest request (QUrl {url});
+ request.setHeader (QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
+ if (!upload.attempts)
+ {
+ ++uploads_started_;
+ }
+ ++upload.attempts;
+ QNetworkReply *reply = transport_->post (request, upload.query.query (QUrl::FullyEncoded).toUtf8 ());
+ connect (reply, &QNetworkReply::finished, this, [this, reply]() { networkReply (reply); });
+ outstanding_requests_.insert (reply, upload);
+ Q_EMIT uploadStatus (QString {"Uploading Spot %1/%2"}.arg (uploads_started_).arg (uploadsToSend ()));
+}
+
+bool WSPRNet::replyAccepted (PendingUpload const& upload, QNetworkReply *reply, QString& server_response) const
+{
+ if (QNetworkReply::NoError != reply->error ())
+ {
+ return false;
+ }
+ server_response = reply->readAll ();
+ return PayloadKind::Status == upload.kind
+ || server_response.contains (QRegExp ("spot\\(s\\) added"));
+}
+
+bool WSPRNet::canRetry (PendingUpload const& upload, QDateTime const& now, int retry_delay_ms) const
+{
+ return upload.attempts < retry_policy_.max_attempts
+ && now.addMSecs (retry_delay_ms) < upload.expires_at;
+}
+
+int WSPRNet::retryDelayMs (PendingUpload const& upload) const
+{
+ int delay = 0;
+ if (!retry_policy_.retry_delays_ms.isEmpty ())
+ {
+ auto const index = qMin (upload.attempts - 1, retry_policy_.retry_delays_ms.size () - 1);
+ delay = retry_policy_.retry_delays_ms[qMax (0, index)];
+ }
+ if (delay <= 0 || retry_policy_.jitter_fraction <= 0.)
+ {
+ return qMax (0, delay);
+ }
+
+#if QT_VERSION >= QT_VERSION_CHECK (5, 10, 0)
+ auto const random = QRandomGenerator::global ()->generateDouble ();
+#else
+ auto const random = qrand () / (RAND_MAX + 1.0);
+#endif
+ auto const factor = 1. - retry_policy_.jitter_fraction
+ + random * retry_policy_.jitter_fraction * 2.;
+ return qMax (0, static_cast<int> (delay * factor));
+}
- if (!spot_queue_.size ())
+int WSPRNet::uploadsToSend () const
+{
+ auto total = uploads_started_;
+ auto count_unstarted = [&total](QQueue<PendingUpload> const& uploads)
+ {
+ for (auto const& upload : uploads)
+ {
+ if (!upload.attempts)
{
- Q_EMIT uploadStatus("done");
- QFile f {m_file};
- if (f.exists ()) f.remove ();
- upload_timer_.stop ();
+ ++total;
}
}
+ };
+ count_unstarted (pending_primary_uploads_);
+ count_unstarted (pending_alternate_uploads_);
+ return qMax (uploads_started_, total);
+}
- qDebug () << QString {"WSPRnet.org %1 outstanding requests"}.arg (m_outstandingRequests.size ());
+void WSPRNet::retryUpload (PendingUpload upload, QDateTime const& now, int retry_delay_ms)
+{
+ upload.next_attempt_at = now.addMSecs (retry_delay_ms);
+ auto& uploads = upload.target == UploadTarget::Primary
+ ? pending_primary_uploads_ : pending_alternate_uploads_;
+ uploads.enqueue (upload);
+ Q_EMIT uploadStatus (QString {"Retrying WSPRNet upload in %1 ms"}.arg (retry_delay_ms));
+ enforcePendingLimit ();
+}
- // delete request object instance on return to the event loop otherwise it is leaked
- reply->deleteLater ();
+void WSPRNet::markAccepted (PendingUpload const& upload)
+{
+ if (UploadSource::File == upload.source)
+ {
+ auto state = file_uploads_.find (upload.file_batch_id);
+ if (state == file_uploads_.end ())
+ {
+ return;
+ }
+ state->accepted.insert (upload.logical_upload_id);
+ state->failed.remove (upload.logical_upload_id);
+ maybeRemoveCompletedFile (upload.file_batch_id);
+ maybeRemoveFailedFileBatch (upload.file_batch_id);
+ }
+}
+
+void WSPRNet::markFailed (PendingUpload const& upload)
+{
+ if (UploadSource::File == upload.source)
+ {
+ auto state = file_uploads_.find (upload.file_batch_id);
+ if (state == file_uploads_.end () || state->accepted.contains (upload.logical_upload_id))
+ {
+ return;
+ }
+ if (!hasPendingFileLeg (upload.file_batch_id, upload.logical_upload_id))
+ {
+ state->failed.insert (upload.logical_upload_id);
+ }
+ maybeRemoveFailedFileBatch (upload.file_batch_id);
+ }
+}
+
+void WSPRNet::maybeRemoveFailedFileBatch (int file_batch_id)
+{
+ auto const state = file_uploads_.constFind (file_batch_id);
+ if (state == file_uploads_.constEnd () || state->failed.isEmpty ())
+ {
+ return;
+ }
+
+ if (state->accepted.size () + state->failed.size () >= state->total)
+ {
+ file_uploads_.remove (file_batch_id);
+ }
+}
+
+void WSPRNet::maybeRemoveCompletedFile (int file_batch_id)
+{
+ if (!file_uploads_.contains (file_batch_id))
+ {
+ return;
+ }
+
+ auto const state = file_uploads_.value (file_batch_id);
+ if (state.total > 0 && state.accepted.size () == state.total)
+ {
+ QFile f {state.snapshot.path};
+ // wsprd can rewrite this scratch file between the check and remove.
+ // The snapshot guard prevents deleting known-new contents.
+ if (f.exists () && fileMatchesSnapshot (state.snapshot))
+ {
+ f.remove ();
+ }
+ file_uploads_.remove (file_batch_id);
+ }
+}
+
+void WSPRNet::maybeFinalize ()
+{
+ if (!upload_session_active_)
+ {
+ return;
+ }
+ if (pending_primary_uploads_.isEmpty () && pending_alternate_uploads_.isEmpty ()
+ && outstanding_requests_.isEmpty ())
+ {
+ uploads_started_ = 0;
+ upload_session_active_ = false;
+ upload_timer_.stop ();
+ Q_EMIT uploadStatus ("done");
}
}
@@ -214,6 +663,10 @@ bool WSPRNet::decodeLine (QString const& line, SpotQueue::value_type& query) con
{
auto const& rx_match = wspr_re.match (line);
if (rx_match.hasMatch ()) {
+ if (line.contains ("<...>")) {
+ return false;
+ }
+
int msgType = 0;
QString msg = rx_match.captured (7);
QString call, grid, dbm;
@@ -299,7 +752,7 @@ auto WSPRNet::urlEncodeNoSpot () const -> SpotQueue::value_type
query.addQueryItem ("dbm", m_dbm);
query.addQueryItem ("version", m_vers);
query.addQueryItem ("mode", encode_mode ());
- return query;;
+ return query;
}
auto WSPRNet::urlEncodeSpot (SpotQueue::value_type& query) const -> SpotQueue::value_type
@@ -314,31 +767,43 @@ auto WSPRNet::urlEncodeSpot (SpotQueue::value_type& query) const -> SpotQueue::v
void WSPRNet::work()
{
- if (spots_to_send_ && spot_queue_.size ())
- {
-#if QT_VERSION < QT_VERSION_CHECK (5, 15, 0)
- if (QNetworkAccessManager::Accessible != network_manager_->networkAccessible ()) {
- // try and recover network access for QNAM
- network_manager_->setNetworkAccessible (QNetworkAccessManager::Accessible);
- }
-#endif
- QNetworkRequest request (QUrl {wsprNetUrl});
- request.setHeader (QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
- auto const& spot = spot_queue_.dequeue ();
- QNetworkReply *reply = network_manager_->post (request, spot.query(QUrl::FullyEncoded).toUtf8());
- connect (reply, &QNetworkReply::finished, this, [this, reply]() { networkReply(reply); });
- m_outstandingRequests << reply;
- Q_EMIT uploadStatus(QString {"Uploading Spot %1/%2"}.arg (spots_to_send_ - spot_queue_.size()).arg (spots_to_send_));
- }
- else
+ auto const now = QDateTime::currentDateTimeUtc ();
+ pruneExpiredUploads (now);
+
+ auto send_ready_upload = [this, &now](QQueue<PendingUpload>& uploads, UploadTarget target)
{
- upload_timer_.stop ();
- }
+ if (hasOutstanding (target))
+ {
+ return;
+ }
+ for (int i = 0; i < uploads.size (); ++i)
+ {
+ if (uploads[i].next_attempt_at <= now)
+ {
+ sendUpload (uploads.takeAt (i));
+ return;
+ }
+ }
+ };
+
+ send_ready_upload (pending_primary_uploads_, UploadTarget::Primary);
+ send_ready_upload (pending_alternate_uploads_, UploadTarget::Alternate);
+
+ scheduleWork ();
+ maybeFinalize ();
}
void WSPRNet::abortOutstandingRequests () {
- spot_queue_.clear ();
- for (auto& request : m_outstandingRequests) {
+ upload_timer_.stop ();
+ pending_primary_uploads_.clear ();
+ pending_alternate_uploads_.clear ();
+ file_uploads_.clear ();
+ uploads_started_ = 0;
+ upload_session_active_ = false;
+
+ auto const requests = outstanding_requests_.keys ();
+ outstanding_requests_.clear ();
+ for (auto& request : requests) {
request->abort ();
}
}
diff --git a/Network/wsprnet.h b/Network/wsprnet.h
index 345f43fd..f7791720 100644
--- a/Network/wsprnet.h
+++ b/Network/wsprnet.h
@@ -4,12 +4,16 @@
#include <QObject>
#include <QTimer>
#include <QString>
-#include <QList>
+#include <QHash>
#include <QUrlQuery>
#include <QQueue>
+#include <QDateTime>
+#include <QVector>
+#include <QByteArray>
+#include <QSet>
-class QNetworkAccessManager;
class QNetworkReply;
+class QNetworkRequest;
class WSPRNet : public QObject
{
@@ -18,13 +22,65 @@ class WSPRNet : public QObject
using SpotQueue = QQueue<QUrlQuery>;
public:
+ // HTTP post seam so tests can upload without constructing QNetworkAccessManager.
+ class Transport
+ {
+ public:
+ virtual ~Transport () = default;
+ virtual QNetworkReply *post (QNetworkRequest const& request, QByteArray const& body) = 0;
+ };
+
+ struct RetryPolicy
+ {
+ int max_attempts = 7;
+ int max_pending = 1024;
+ int ttl_ms = 60 * 60 * 1000;
+ double jitter_fraction = 0.25;
+ QVector<int> retry_delays_ms {15000, 60000, 120000, 300000, 600000, 1200000};
+ };
+
+ struct StationContext
+ {
+ StationContext () = default;
+ StationContext (QString const& call, QString const& grid, QString const& rfreq, QString const& tfreq,
+ QString const& mode, float TR_period, QString const& tpct, QString const& dbm,
+ QString const& version)
+ : call {call}
+ , grid {grid}
+ , rfreq {rfreq}
+ , tfreq {tfreq}
+ , mode {mode}
+ , TR_period {TR_period}
+ , tpct {tpct}
+ , dbm {dbm}
+ , version {version}
+ {
+ }
+
+ QString call;
+ QString grid;
+ QString rfreq;
+ QString tfreq;
+ QString mode;
+ float TR_period = 0.F;
+ QString tpct;
+ QString dbm;
+ QString version;
+ };
+
explicit WSPRNet (QObject *parent = nullptr);
+ WSPRNet (Transport *transport, RetryPolicy retry_policy,
+ bool take_transport_ownership, QObject *parent = nullptr);
+ ~WSPRNet ();
void upload (QString const& call, QString const& grid, QString const& rfreq, QString const& tfreq,
- QString const& mode, float TR_peirod, QString const& tpct, QString const& dbm,
+ QString const& mode, float TR_period, QString const& tpct, QString const& dbm,
QString const& version, QString const& fileName);
void post (QString const& call, QString const& grid, QString const& rfreq, QString const& tfreq,
QString const& mode, float TR_period, QString const& tpct, QString const& dbm,
QString const& version, QString const& decode_text = QString {});
+ void queueWsprFile (StationContext const& context, QString const& file_name);
+ void queueFst4wDecode (StationContext const& context, QString const& decode_text);
+ void flush (StationContext const& context);
signals:
void uploadStatus (QString);
@@ -34,27 +90,88 @@ public slots:
void abortOutstandingRequests ();
private:
+ enum class UploadSource {Direct, File};
+ enum class PayloadKind {Spot, Status};
+ enum class UploadTarget {Primary, Alternate};
+
+ struct PendingUpload
+ {
+ QUrlQuery query;
+ UploadSource source;
+ PayloadKind kind;
+ QString source_file;
+ int file_batch_id;
+ QDateTime queued_at;
+ QDateTime expires_at;
+ QDateTime next_attempt_at;
+ int attempts;
+ UploadTarget target;
+ int logical_upload_id;
+ };
+
+ struct FileSnapshot
+ {
+ QString path;
+ qint64 size = -1;
+ QByteArray hash;
+ };
+
+ struct FileUploadState
+ {
+ FileSnapshot snapshot;
+ int total = 0;
+ QSet<int> accepted;
+ QSet<int> failed;
+ };
+
+ void applyContext (StationContext const& context);
+ FileSnapshot snapshotFile (QString const& file_name) const;
+ bool fileMatchesSnapshot (FileSnapshot const& snapshot) const;
+ bool hasPendingFileLeg (int file_batch_id, int logical_upload_id) const;
+ bool hasOutstanding (UploadTarget target) const;
bool decodeLine (QString const& line, SpotQueue::value_type& query) const;
SpotQueue::value_type urlEncodeNoSpot () const;
SpotQueue::value_type urlEncodeSpot (SpotQueue::value_type& spot) const;
QString encode_mode () const;
+ void enqueueUpload (QUrlQuery const& query, UploadSource source, PayloadKind kind, QString const& source_file = QString {}, int file_batch_id = 0);
+ int beginFileBatch (FileSnapshot const& snapshot);
+ void startUploadSession ();
+ void scheduleWork ();
+ void pruneExpiredUploads (QDateTime const& now);
+ void enforcePendingLimit ();
+ void sendUpload (PendingUpload upload);
+ bool replyAccepted (PendingUpload const& upload, QNetworkReply *reply, QString& server_response) const;
+ bool canRetry (PendingUpload const& upload, QDateTime const& now, int retry_delay_ms) const;
+ int retryDelayMs (PendingUpload const& upload) const;
+ int uploadsToSend () const;
+ void retryUpload (PendingUpload upload, QDateTime const& now, int retry_delay_ms);
+ void markAccepted (PendingUpload const& upload);
+ void markFailed (PendingUpload const& upload);
+ void maybeRemoveFailedFileBatch (int file_batch_id);
+ void maybeRemoveCompletedFile (int file_batch_id);
+ void maybeFinalize ();
- QNetworkAccessManager * network_manager_;
- QList<QNetworkReply *> m_outstandingRequests;
+ Transport * transport_;
+ bool owns_transport_;
+ RetryPolicy retry_policy_;
+ QHash<QNetworkReply *, PendingUpload> outstanding_requests_;
+ QHash<int, FileUploadState> file_uploads_;
QString m_call;
- QString m_grid;;
+ QString m_grid;
QString m_rfreq;
QString m_tfreq;
QString m_mode;
QString m_tpct;
QString m_dbm;
QString m_vers;
- QString m_file;
float TR_period_;
- int spots_to_send_;
- SpotQueue spot_queue_;
+ int uploads_started_;
+ int next_file_batch_id_;
+ int next_logical_upload_id_;
+ QQueue<PendingUpload> pending_primary_uploads_;
+ QQueue<PendingUpload> pending_alternate_uploads_;
QTimer upload_timer_;
- int m_uploadType;
+ bool upload_session_active_;
};
#endif // WSPRNET_H