diff options
Diffstat (limited to 'Network')
| -rw-r--r-- | Network/Cloudlog.cpp | 965 | ||||
| -rw-r--r-- | Network/Cloudlog.hpp | 119 | ||||
| -rw-r--r-- | Network/CloudlogConfiguration.hpp | 16 | ||||
| -rw-r--r-- | Network/DecodedTime.cpp | 65 | ||||
| -rw-r--r-- | Network/DecodedTime.hpp | 13 | ||||
| -rw-r--r-- | Network/FileDownload.cpp | 8 | ||||
| -rw-r--r-- | Network/FoxVerifier.cpp | 3 | ||||
| -rw-r--r-- | Network/MessageClient.cpp | 468 | ||||
| -rw-r--r-- | Network/MessageClient.hpp | 15 | ||||
| -rw-r--r-- | Network/Network.pri | 21 | ||||
| -rw-r--r-- | Network/NetworkMessage.hpp | 70 | ||||
| -rw-r--r-- | Network/PSKReporter.cpp | 533 | ||||
| -rw-r--r-- | Network/PSKReporter.hpp | 16 | ||||
| -rw-r--r-- | Network/PSKReporterConfiguration.cpp | 18 | ||||
| -rw-r--r-- | Network/PSKReporterIPFIX.cpp | 294 | ||||
| -rw-r--r-- | Network/PSKReporterIPFIX.hpp | 47 | ||||
| -rw-r--r-- | Network/eqsl.cpp | 2 | ||||
| -rw-r--r-- | Network/tests/PSKReporter/PSKReporter.IESpec | 12 | ||||
| -rw-r--r-- | Network/tests/PSKReporter/listener.py | 94 | ||||
| -rw-r--r-- | Network/tests/PSKReporter/python-ipfix.patch | 64 | ||||
| -rw-r--r-- | Network/wsprnet.cpp | 699 | ||||
| -rw-r--r-- | Network/wsprnet.h | 137 |
22 files changed, 2828 insertions, 851 deletions
diff --git a/Network/Cloudlog.cpp b/Network/Cloudlog.cpp index ea9ac395..1ebb6eea 100644 --- a/Network/Cloudlog.cpp +++ b/Network/Cloudlog.cpp @@ -1,36 +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 @@ -39,137 +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")); - 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", "WSJT-X Cloudlog API"); - 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 abort () + void startXmlAuth () { - if (reply_ && reply_->isRunning ()) + 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}); + }); + } + + template<typename Continue> + void handleAuthResult (AuthResult const& result, Continue continueProbe) + { + 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)) { - reply_->abort (); + 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) + { + 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 5e64d5c5..b91713ee 100644 --- a/Network/PSKReporter.cpp +++ b/Network/PSKReporter.cpp @@ -7,26 +7,22 @@ // Reports will be sent in batch mode every 5 minutes. #include <fstream> -#include <iostream> -#include <cmath> +#include <string> +#include <ctime> #include <QObject> #include <QString> #include <QDateTime> #include <QSharedPointer> #include <QUdpSocket> #include <QTcpSocket> -#include <QHostInfo> #include <QQueue> -#include <QByteArray> -#include <QDataStream> #include <QTimer> -#include <QDir> #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) #include <QRandomGenerator> #endif #include "Logger.hpp" -#include "Configuration.hpp" +#include "PSKReporterIPFIX.hpp" #include "pimpl_impl.hpp" @@ -36,21 +32,17 @@ 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 - bool ALIGNMENT_PADDING {true}; - int MIN_PAYLOAD_LENGTH {508}; - int MAX_PAYLOAD_LENGTH {10000}; + int MAX_PENDING_SPOTS {2048}; int CACHE_TIMEOUT {300}; // default to 5 minutes for repeating spots QMap<QString, time_t> spot_cache; -} -static int added; -static int removed; +#ifdef DEBUGPSK + int added; + int removed; +#endif +} class PSKReporter::impl final : public QObject @@ -60,15 +52,13 @@ class PSKReporter::impl final using logger_type = boost::log::sources::severity_channel_logger_mt<boost::log::trivial::severity_level>; public: - impl (PSKReporter * self, Configuration const * config, QString const& program_info) + impl (PSKReporter * self, PSKReporter::Options const& options) : logger_ {boost::log::keywords::channel = "PSKRPRT"} , self_ {self} - , config_ {config} + , options_ {options} , sequence_number_ {0u} , send_descriptors_ {0} - , send_receiver_data_ {0} , flush_counter_ {0u} - , prog_id_ {program_info} { #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) observation_id_ = qrand(); @@ -79,9 +69,8 @@ public: // This timer sets the interval to check for spots to send. connect (&report_timer_, &QTimer::timeout, [this] () {send_report ();}); - // This timer repeats the sending of IPFIX templates and receiver - // information if we are using UDP, in case server has been - // restarted ans lost cached information. + // UDP has no session state, so templates are repeated periodically in case + // the collector restarted and lost its template cache. connect (&descriptor_timer_, &QTimer::timeout, [this] () { if (socket_ && QAbstractSocket::UdpSocket == socket_->socketType ()) @@ -89,18 +78,16 @@ public: LOG_LOG_LOCATION (logger_, trace, "enable descriptor resend"); // send templates again send_descriptors_ = 3; // three times - // send receiver data set again - send_receiver_data_ = 3; // three times } }); - eclipse_load(config->data_dir ().absoluteFilePath ("eclipse.txt")); + eclipse_load(options_.eclipse_file_path); } void check_connection () { if (!socket_ || QAbstractSocket::UnconnectedState == socket_->state () - || (socket_->socketType () != (config_->psk_reporter_tcpip () ? QAbstractSocket::TcpSocket : QAbstractSocket::UdpSocket))) + || (socket_->socketType () != (options_.use_tcpip ? QAbstractSocket::TcpSocket : QAbstractSocket::UdpSocket))) { // we need to create the appropriate socket if (socket_ @@ -127,7 +114,7 @@ public: void handle_socket_error (QAbstractSocket::SocketError e) { - LOG_LOG_LOCATION (logger_, warning, "socket error: " << socket_->errorString ()); + LOG_LOG_LOCATION (logger_, warning, "socket error: " << qPrintable (socket_->errorString ())); switch (e) { case QAbstractSocket::RemoteHostClosedError: @@ -148,19 +135,17 @@ public: { // Using deleteLater for the deleter as we may eventually // be called from the disconnected handler above. - if (config_->psk_reporter_tcpip ()) + if (options_.use_tcpip) { LOG_LOG_LOCATION (logger_, trace, "create TCP/IP socket"); socket_.reset (new QTcpSocket, &QObject::deleteLater); send_descriptors_ = 1; - send_receiver_data_ = 1; } else { LOG_LOG_LOCATION (logger_, trace, "create UDP/IP socket"); socket_.reset (new QUdpSocket, &QObject::deleteLater); send_descriptors_ = 3; - send_receiver_data_ = 3; } #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) @@ -173,12 +158,15 @@ 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 << " 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 ()) { - report_timer_.start (MIN_SEND_INTERVAL+1 * 1000); // we add 1 to give some more randomization + report_timer_.start ((MIN_SEND_INTERVAL + 1) * 1000); } if (!descriptor_timer_.isActive ()) { @@ -198,7 +186,6 @@ public: } void send_report (bool send_residue = false); - void build_preamble (QDataStream&); void eclipse_load(QString filename); bool eclipse_active(QDateTime now = QDateTime::currentDateTime()); @@ -209,389 +196,139 @@ public: return flush; } - QString getStringFromQDateTime(const QString& dateTimeString, const QString& format) - { - QDateTime dateTime = QDateTime::fromString(dateTimeString, format); - return dateTime.toString(); - } - QList<QDateTime> eclipseDates; logger_type mutable logger_; PSKReporter * self_; - Configuration const * config_; + PSKReporter::Options options_; QSharedPointer<QAbstractSocket> socket_; - int dns_lookup_id_; - QByteArray payload_; quint32 sequence_number_; int send_descriptors_; - // Currently PSK Reporter requires that a receiver data set is sent - // in every data flow. This memeber variable can be used to only - // send that information at session start (3 times for UDP), when it - // changes (3 times for UDP), or once per hour (3 times) if using - // UDP. Uncomment the relevant code to enable that fuctionality. - int send_receiver_data_; - unsigned flush_counter_; quint32 observation_id_; QString rx_call_; QString rx_grid_; QString rx_ant_; QString rigInformation_; - QString prog_id_; - QByteArray tx_data_; - QByteArray tx_residue_; - struct Spot - { - bool operator == (Spot const& rhs) - { - return - call_ == rhs.call_ - && grid_ == rhs.grid_ - && mode_ == rhs.mode_ - && std::abs (Radio::FrequencyDelta (freq_ - rhs.freq_)) < 50; - } - - QString call_; - QString grid_; - int snr_; - Radio::Frequency freq_; - QString mode_; - QDateTime time_; - }; - QQueue<Spot> spots_; + QQueue<PSKReporterIPFIX::Spot> spots_; QTimer report_timer_; QTimer descriptor_timer_; }; #include "PSKReporter.moc" -namespace -{ - void writeUtfString (QDataStream& out, QString const& s) - { - auto const& utf = s.toUtf8 ().left (254); - out << quint8 (utf.size ()); - out.writeRawData (utf, utf.size ()); - } - - int num_pad_bytes (int len) - { - return ALIGNMENT_PADDING ? (4 - len % 4) % 4 : 0; - } - - void set_length (QDataStream& out, QByteArray& b) - { - // pad with nulls modulo 4 - auto pad_len = num_pad_bytes (b.size ()); - out.writeRawData (QByteArray {pad_len, '\0'}.constData (), pad_len); - auto pos = out.device ()->pos (); - out.device ()->seek (sizeof (quint16)); - // insert length - out << static_cast<quint16> (b.size ()); - out.device ()->seek (pos); - } -} - bool PSKReporter::impl::eclipse_active(QDateTime timeutc) { - qDebug() << timeutc; + Q_UNUSED (timeutc); #ifdef DEBUGECLIPSE - std::ofstream mylog("/temp/eclipse.log", std::ios_base::app); + std::ofstream mylog("/temp/eclipse.log", std::ios_base::app); #endif - QDateTime dateNow = QDateTime::currentDateTimeUtc(); - for (int i=0; i< eclipseDates.size(); ++i) + QDateTime const dateNow = QDateTime::currentDateTimeUtc (); + for (auto const& check : eclipseDates) { - QDateTime check = eclipseDates.at(i); // already in UTC time - // +- 6 hour window - qint64 secondsDiff = qAbs(check.secsTo(dateNow)); - if (secondsDiff <= 3600*6) // 6 hour check + auto const secondsDiff = qAbs (check.secsTo (dateNow)); + if (secondsDiff <= 3600 * 6) { #ifdef DEBUGECLIPSE - mylog << dateNow.toString(Qt::ISODate) << " Eclipse! " << "secondsDiff=" << secondsDiff << std::endl; + mylog << dateNow.toString(Qt::ISODate) << " Eclipse! " << "secondsDiff=" << secondsDiff << std::endl; #endif - return true; + return true; } } #ifdef DEBUGECLIPSE - mylog << timeutc.toString("yyyy-MM-dd HH:mm:ss") << " no eclipse" << "\n"; + mylog << timeutc.toString("yyyy-MM-dd HH:mm:ss") << " no eclipse" << "\n"; #endif - return false; + return false; } void PSKReporter::impl::eclipse_load(QString eclipse_file) { - std::ifstream fs(qPrintable(eclipse_file)); - std::string mydate,mytime,myline; + std::ifstream fs(qPrintable(eclipse_file)); #ifdef DEBUGECLIPSE - std::ofstream mylog("c:/temp/eclipse.log"); - mylog << "eclipse_file=" << eclipse_file << std::endl; + std::ofstream mylog("/temp/eclipse.log"); + mylog << "eclipse_file=" << qPrintable(eclipse_file) << std::endl; #endif - if (fs.is_open()) + std::string line; + while (std::getline (fs, line)) { - while(!fs.eof()) - { - std::getline(fs, myline); - if (myline[0] != '#' && myline.length() > 2) // make sure to skip blank lines - { - //QString format = "yyyy-MM-dd hh:mm:ss"; - QDateTime qdate = QDateTime::fromString(QString::fromStdString(myline), Qt::ISODate); - QDateTime now = QDateTime::currentDateTimeUtc(); - // only add the date if we can cover the whole 12 hours - //if (now < qdate.toUTC().addSecs(-3600*6)) - eclipseDates.append(qdate); -#ifdef DEBUGECLIPSE - //else - // mylog << "not adding " << myline << std::endl; -#endif - - } + if (line.size () <= 2 || line[0] == '#') + { + continue; + } + auto const eclipse = QDateTime::fromString(QString::fromStdString(line), Qt::ISODate); + if (eclipse.isValid ()) + { + eclipseDates.append(eclipse); + } #ifdef DEBUGECLIPSE - mylog << myline << std::endl; + mylog << line << std::endl; #endif - } } #ifdef DEBUGECLIPSE - if (eclipse_active(QDateTime::currentDateTime().toUTC())) mylog << "Eclipse is active" << std::endl; - else mylog << "Eclipse is not active" << std::endl; + if (eclipse_active(QDateTime::currentDateTime().toUTC())) mylog << "Eclipse is active" << std::endl; + else mylog << "Eclipse is not active" << std::endl; #endif } -void PSKReporter::impl::build_preamble (QDataStream& message) -{ - // Message Header - message - << quint16 (10u) // Version Number - << quint16 (0u) // Length (place-holder filled in later) - << quint32 (0u) // Export Time (place-holder filled in later) - << ++sequence_number_ // Sequence Number - << observation_id_; // Observation Domain ID - LOG_LOG_LOCATION (logger_, trace, "#: " << sequence_number_); - - if (send_descriptors_) - { - --send_descriptors_; - { - // Sender Information descriptor - QByteArray descriptor; - QDataStream out {&descriptor, QIODevice::WriteOnly}; - out - << quint16 (2u) // Template Set ID - << quint16 (0u) // Length (place-holder) - << quint16 (0x50e3) // Link ID - << quint16 (7u) // Field Count - << quint16 (0x8000 + 1u) // Option 1 Information Element ID (senderCallsign) - << quint16 (0xffff) // Option 1 Field Length (variable) - << quint32 (30351u) // Option 1 Enterprise Number - << quint16 (0x8000 + 5u) // Option 2 Information Element ID (frequency) - << quint16 (5u) // Option 2 Field Length - << quint32 (30351u) // Option 2 Enterprise Number - << quint16 (0x8000 + 6u) // Option 3 Information Element ID (sNR) - << quint16 (1u) // Option 3 Field Length - << quint32 (30351u) // Option 3 Enterprise Number - << quint16 (0x8000 + 10u) // Option 4 Information Element ID (mode) - << quint16 (0xffff) // Option 4 Field Length (variable) - << quint32 (30351u) // Option 4 Enterprise Number - << quint16 (0x8000 + 3u) // Option 5 Information Element ID (senderLocator) - << quint16 (0xffff) // Option 5 Field Length (variable) - << quint32 (30351u) // Option 5 Enterprise Number - << quint16 (0x8000 + 11u) // Option 6 Information Element ID (informationSource) - << quint16 (1u) // Option 6 Field Length - << quint32 (30351u) // Option 6 Enterprise Number - << quint16 (150u) // Option 7 Information Element ID (dateTimeSeconds) - << quint16 (4u); // Option 7 Field Length - // insert Length and move to payload - set_length (out, descriptor); - message.writeRawData (descriptor.constData (), descriptor.size ()); - } - { - // Receiver Information descriptor - QByteArray descriptor; - QDataStream out {&descriptor, QIODevice::WriteOnly}; - out - << quint16 (3u) // Options Template Set ID - << quint16 (0u) // Length (place-holder) - << quint16 (0x50e2) // Link ID - << quint16 (5u) // Field Count - << quint16 (0u) // Scope Field Count - << quint16 (0x8000 + 2u) // Option 1 Information Element ID (receiverCallsign) - << quint16 (0xffff) // Option 1 Field Length (variable) - << quint32 (30351u) // Option 1 Enterprise Number - << quint16 (0x8000 + 4u) // Option 2 Information Element ID (receiverLocator) - << quint16 (0xffff) // Option 2 Field Length (variable) - << quint32 (30351u) // Option 2 Enterprise Number - << quint16 (0x8000 + 8u) // Option 3 Information Element ID (decodingSoftware) - << quint16 (0xffff) // Option 3 Field Length (variable) - << quint32 (30351u) // Option 3 Enterprise Number - << quint16 (0x8000 + 9u) // Option 4 Information Element ID (antennaInformation) - << quint16 (0xffff) // Option 4 Field Length (variable) - << quint32 (30351u) // Option 5 Enterprise Number - << quint16 (0x8000 + 13u)// Option 5 Information Element ID (rigInformation) - << quint16 (0xffff) // Option 5 Field Length (variable) - << quint32 (30351u); // Option 4 Enterprise Number - // insert Length - set_length (out, descriptor); - message.writeRawData (descriptor.constData (), descriptor.size ()); - LOG_LOG_LOCATION (logger_, debug, "sent descriptors"); - } - } - - // if (send_receiver_data_) - { - // --send_receiver_data_; - - // Receiver information - QByteArray data; - QDataStream out {&data, QIODevice::WriteOnly}; - - // Set Header - out - << quint16 (0x50e2) // Template ID - << quint16 (0u); // Length (place-holder) - - // Set data - writeUtfString (out, rx_call_); - writeUtfString (out, rx_grid_); - writeUtfString (out, prog_id_); - writeUtfString (out, rx_ant_); - writeUtfString (out, rigInformation_); - - // insert Length and move to payload - set_length (out, data); - message.writeRawData (data.constData (), data.size ()); - LOG_LOG_LOCATION (logger_, debug, "sent local information"); - } -} - void PSKReporter::impl::send_report (bool send_residue) { LOG_LOG_LOCATION (logger_, trace, "sending residue: " << send_residue); - if (QAbstractSocket::ConnectedState != socket_->state ()) return; - - QDataStream message {&payload_, QIODevice::WriteOnly | QIODevice::Append}; - QDataStream tx_out {&tx_data_, QIODevice::WriteOnly | QIODevice::Append}; - - if (!payload_.size ()) + check_connection (); + if (!socket_ || QAbstractSocket::ConnectedState != socket_->state ()) { - // Build header, optional descriptors, and receiver information - build_preamble (message); + return; } auto flush = flushing () || send_residue; - while (spots_.size () || flush) + if (!spots_.size () && !flush && !send_descriptors_) { - if (!payload_.size ()) - { - // Build header, optional descriptors, and receiver information - build_preamble (message); - } + return; + } - if (!tx_data_.size () && (spots_.size () || tx_residue_.size ())) - { - // Set Header - tx_out - << quint16 (0x50e3) // Template ID - << quint16 (0u); // Length (place-holder) - } + QList<PSKReporterIPFIX::Spot> spots; + while (!spots_.isEmpty ()) + { + spots.append (spots_.dequeue ()); + } - // insert any residue - if (tx_residue_.size ()) - { - tx_out.writeRawData (tx_residue_.constData (), tx_residue_.size ()); - LOG_LOG_LOCATION (logger_, debug, "sent residue"); - tx_residue_.clear (); - } + bool const include_descriptors = send_descriptors_ > 0; + if (include_descriptors) + { + --send_descriptors_; + } - LOG_LOG_LOCATION (logger_, debug, "pending spots: " << spots_.size ()); - while (spots_.size () || flush) - { - auto tx_data_size = tx_data_.size (); - if (spots_.size ()) - { - auto const& spot = spots_.dequeue (); - - // Sender information - writeUtfString (tx_out, spot.call_); - uint8_t data[5]; - long long int i64 = spot.freq_; - data[0] = ( i64 & 0xff); - data[1] = ((i64 >> 8) & 0xff); - data[2] = ((i64 >> 16) & 0xff); - data[3] = ((i64 >> 24) & 0xff); - data[4] = ((i64 >> 32) & 0xff); - tx_out // BigEndian - << static_cast<uint8_t> (data[4]) - << static_cast<uint8_t> (data[3]) - << static_cast<uint8_t> (data[2]) - << static_cast<uint8_t> (data[1]) - << static_cast<uint8_t> (data[0]) - << static_cast<qint8> (spot.snr_); - writeUtfString (tx_out, spot.mode_); - writeUtfString (tx_out, spot.grid_); - tx_out - << quint8 (1u) // REPORTER_SOURCE_AUTOMATIC - << static_cast<quint32> ( + auto const max_payload_bytes = options_.use_tcpip + ? PSKReporterIPFIX::maxTcpIpfixPayloadBytes () + : PSKReporterIPFIX::maxUdpIpfixPayloadBytes (); + auto const packets = PSKReporterIPFIX::buildPackets ( + {rx_call_, rx_grid_, options_.program_info, rx_ant_, rigInformation_} + , spots + , include_descriptors + , sequence_number_ + , observation_id_ + , static_cast<quint32> ( #if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0) - spot.time_.toSecsSinceEpoch () + QDateTime::currentDateTime ().toSecsSinceEpoch () #else - spot.time_.toMSecsSinceEpoch () / 1000 + QDateTime::currentDateTime ().toMSecsSinceEpoch () / 1000 #endif - ); - } - - auto len = payload_.size () + tx_data_.size (); - len += num_pad_bytes (tx_data_.size ()); - len += num_pad_bytes (len); - if (len > MAX_PAYLOAD_LENGTH // our upper datagram size limit - || (!spots_.size () && len > MIN_PAYLOAD_LENGTH) // spots drained and above lower datagram size limit - || (flush && !spots_.size ())) // send what we have, possibly no spots - { - if (tx_data_.size ()) - { - if (len <= MAX_PAYLOAD_LENGTH) - { - tx_data_size = tx_data_.size (); - } - QByteArray tx {tx_data_.left (tx_data_size)}; - QDataStream out {&tx, QIODevice::WriteOnly | QIODevice::Append}; - // insert Length - set_length (out, tx); - message.writeRawData (tx.constData (), tx.size ()); - } - - // insert Length and Export Time - set_length (message, payload_); - message.device ()->seek (2 * sizeof (quint16)); - message << static_cast<quint32> ( -#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0) - QDateTime::currentDateTime ().toSecsSinceEpoch () -#else - QDateTime::currentDateTime ().toMSecsSinceEpoch () / 1000 -#endif - ); - - // Send data to PSK Reporter site - socket_->write (payload_); // TODO: handle errors - LOG_LOG_LOCATION (logger_, debug, "sent spots"); - flush = false; // break loop - message.device ()->seek (0u); - payload_.clear (); // Fresh message - // Save unsent spots - tx_residue_ = tx_data_.right (tx_data_.size () - tx_data_size); - tx_out.device ()->seek (0u); - tx_data_.clear (); - break; - } - } - LOG_LOG_LOCATION (logger_, debug, "remaining spots: " << spots_.size ()); + ) + , max_payload_bytes); + + for (auto const& packet : packets) + { + Q_ASSERT (packet.payload.size () <= max_payload_bytes); + socket_->write (packet.payload); + sequence_number_ += packet.spot_count; + LOG_LOG_LOCATION (logger_, debug, "sent packet bytes: " << packet.payload.size () << " spots: " << packet.spot_count); } } -PSKReporter::PSKReporter (Configuration const * config, QString const& program_info) - : m_ {this, config, program_info} +PSKReporter::PSKReporter (Options const& options) + : m_ {this, options} { - LOG_LOG_LOCATION (m_->logger_, trace, "Started for: " << program_info); + LOG_LOG_LOCATION (m_->logger_, trace, "Started for: " << qPrintable (options.program_info)); } PSKReporter::~PSKReporter () @@ -613,13 +350,11 @@ bool PSKReporter::eclipse_active(QDateTime now) void PSKReporter::setLocalStation (QString const& call, QString const& gridSquare, QString const& antenna, QString const& rigInformation) { - LOG_LOG_LOCATION (m_->logger_, trace, "call: " << call << " grid: " << gridSquare << " ant: " << antenna); + LOG_LOG_LOCATION (m_->logger_, trace, "call: " << qPrintable (call) << " grid: " << qPrintable (gridSquare) << " ant: " << qPrintable (antenna)); m_->check_connection (); - if (call != m_->rx_call_ || gridSquare != m_->rx_grid_ || antenna != m_->rx_ant_) + if (call != m_->rx_call_ || gridSquare != m_->rx_grid_ || antenna != m_->rx_ant_ || rigInformation != m_->rigInformation_) { LOG_LOG_LOCATION (m_->logger_, trace, "updating information"); - m_->send_receiver_data_ = m_->socket_ - && QAbstractSocket::UdpSocket == m_->socket_->socketType () ? 3 : 1; m_->rx_call_ = call; m_->rx_grid_ = gridSquare; m_->rx_ant_ = antenna; @@ -630,56 +365,58 @@ void PSKReporter::setLocalStation (QString const& call, QString const& gridSquar bool PSKReporter::addRemoteStation (QString const& call, QString const& grid, Radio::Frequency freq , QString const& mode, int snr, QDateTime qSpotTime) { - LOG_LOG_LOCATION (m_->logger_, trace, "call: " << call << " grid: " << grid << " freq: " << freq << " mode: " << mode << " snr: " << snr); + LOG_LOG_LOCATION (m_->logger_, trace, "call: " << qPrintable (call) << " grid: " << qPrintable (grid) << " freq: " << freq << " mode: " << qPrintable (mode) << " snr: " << snr); m_->check_connection (); - if (m_->socket_ && m_->socket_->isValid ()) - { - if (QAbstractSocket::UnconnectedState == m_->socket_->state ()) - { - reconnect (); - } - // remove any earlier spots of this call to reduce pskreporter load + // remove any earlier spots of this call to reduce pskreporter load +#ifdef DEBUGPSK + static std::fstream fs; + if (!fs.is_open()) fs.open("/temp/psk.log", std::fstream::in | std::fstream::out | std::fstream::app); +#endif #ifdef DEBUGPSK - static std::fstream fs; - if (!fs.is_open()) fs.open("/temp/psk.log", std::fstream::in | std::fstream::out | std::fstream::app); + added++; #endif - added++; - QDateTime qdateNow = QDateTime::currentDateTime().toUTC(); - // we allow all spots through +/- 6 hours around an eclipse for the HamSCI group - if (!spot_cache.contains(call) || freq > 49000000 || eclipse_active(qdateNow)) // then it's a new spot - { - m_->spots_.enqueue ({call, grid, snr, freq, mode, qSpotTime}); - spot_cache.insert(call, time(NULL)); + QDateTime qdateNow = QDateTime::currentDateTime().toUTC(); + // We allow all spots through +/- 6 hours around an eclipse for the HamSCI group. + if (!spot_cache.contains(call) || freq > 49000000 || eclipse_active(qdateNow)) + { + m_->spots_.enqueue ({call, grid, snr, freq, mode, qSpotTime}); + spot_cache.insert(call, time(NULL)); #ifdef DEBUGPSK - if (fs.is_open()) fs << "Adding " << call << " freq=" << freq << " " << spot_cache[call] << " count=" << m_->spots_.count() << std::endl; + if (fs.is_open()) fs << "Adding " << call << " freq=" << freq << " " << spot_cache[call] << " count=" << m_->spots_.count() << std::endl; #endif - } - else if (time(NULL) - spot_cache[call] > CACHE_TIMEOUT) // then the cache has expired - { - m_->spots_.enqueue ({call, grid, snr, freq, mode, qSpotTime}); + } + else if (time(NULL) - spot_cache[call] > CACHE_TIMEOUT) + { + m_->spots_.enqueue ({call, grid, snr, freq, mode, qSpotTime}); #ifdef DEBUGPSK - if (fs.is_open()) fs << "Adding # " << call << spot_cache[call] << " count=" << m_->spots_.count() << std::endl; + if (fs.is_open()) fs << "Adding # " << call << spot_cache[call] << " count=" << m_->spots_.count() << std::endl; #endif - spot_cache[call] = time(NULL); - } - else - { - removed++; + spot_cache[call] = time(NULL); + } + else + { #ifdef DEBUGPSK - if (fs.is_open()) fs << "Removing " << call << " " << time(NULL) << " reduction=" << removed/(double)added*100 << "%" << std::endl; + removed++; + if (fs.is_open()) fs << "Removing " << call << " " << time(NULL) << " reduction=" << removed/(double)added*100 << "%" << std::endl; #endif - } - // remove cached items over 10 minutes old to save a little memory - QMapIterator<QString, time_t> i(spot_cache); - time_t tmptime = time(NULL); - while(i.hasNext()) { - i.next(); - if (tmptime - i.value() > 600) spot_cache.remove(i.key()); - } - return true; } - return false; + + bool accepted = true; + while (m_->spots_.size () > MAX_PENDING_SPOTS) + { + m_->spots_.dequeue (); + accepted = false; + LOG_LOG_LOCATION (m_->logger_, warning, "PSKReporter pending spot queue exceeded " << MAX_PENDING_SPOTS << "; dropped oldest spot"); + } + + QMapIterator<QString, time_t> i(spot_cache); + time_t tmptime = time(NULL); + while(i.hasNext()) { + i.next(); + if (tmptime - i.value() > 600) spot_cache.remove(i.key()); + } + return accepted; } void PSKReporter::sendReport (bool last) diff --git a/Network/PSKReporter.hpp b/Network/PSKReporter.hpp index 4b2175c8..3b1f4f13 100644 --- a/Network/PSKReporter.hpp +++ b/Network/PSKReporter.hpp @@ -2,6 +2,8 @@ #define PSK_REPORTER_HPP_ #include <QObject> +#include <QDateTime> +#include <QString> #include "Radio.hpp" #include "pimpl_h.hpp" @@ -14,16 +16,24 @@ class PSKReporter final Q_OBJECT public: + struct Options + { + 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); + explicit PSKReporter (Options const& options); ~PSKReporter (); void reconnect (); void setLocalStation (QString const& call, QString const& grid, QString const& antenna, QString const& rigInformation); - // - // Returns false if PSK Reporter connection is not available - // + // Returns false if accepting the spot required dropping an older pending spot. bool addRemoteStation (QString const& call, QString const& grid, Radio::Frequency freq, QString const& mode, int snr, QDateTime spotTime); // diff --git a/Network/PSKReporterConfiguration.cpp b/Network/PSKReporterConfiguration.cpp new file mode 100644 index 00000000..9369e911 --- /dev/null +++ b/Network/PSKReporterConfiguration.cpp @@ -0,0 +1,18 @@ +#include "PSKReporter.hpp" + +#include <QDir> + +#include "Configuration.hpp" + +namespace +{ + PSKReporter::Options options_from_config (Configuration const * config, QString const& program_info) + { + return {config->psk_reporter_tcpip (), config->data_dir ().absoluteFilePath ("eclipse.txt"), program_info}; + } +} + +PSKReporter::PSKReporter (Configuration const * config, QString const& program_info) + : PSKReporter {options_from_config (config, program_info)} +{ +} diff --git a/Network/PSKReporterIPFIX.cpp b/Network/PSKReporterIPFIX.cpp new file mode 100644 index 00000000..27b3aea2 --- /dev/null +++ b/Network/PSKReporterIPFIX.cpp @@ -0,0 +1,294 @@ +#include "PSKReporterIPFIX.hpp" + +#include <QBuffer> +#include <QDataStream> +#include <QtGlobal> + +namespace +{ + constexpr int MAX_UDP_IP_PACKET_BYTES = 1000; + constexpr int IPV6_HEADER_BYTES = 40; + constexpr int UDP_HEADER_BYTES = 8; + constexpr int MAX_UDP_IPFIX_PAYLOAD_BYTES = MAX_UDP_IP_PACKET_BYTES - IPV6_HEADER_BYTES - UDP_HEADER_BYTES; + constexpr int MAX_TCP_IPFIX_PAYLOAD_BYTES = 0xffff; + constexpr bool ALIGNMENT_PADDING = true; + + constexpr int CALLSIGN_LIMIT = 32; + constexpr int LOCATOR_LIMIT = 16; + constexpr int MODE_LIMIT = 16; + constexpr int PROGRAM_INFO_LIMIT = 80; + constexpr int ANTENNA_LIMIT = 128; + constexpr int RIG_INFORMATION_LIMIT = 128; + + // PSK Reporter uses enterprise-specific IPFIX elements under PEN 30351. + // Template 0x50e3 describes sender/spot records; template 0x50e2 describes + // receiver metadata, with receiverCallsign as the options-template scope. + constexpr quint32 PSK_REPORTER_PEN = 30351; + constexpr quint16 SENDER_TEMPLATE_ID = 0x50e3; + constexpr quint16 RECEIVER_TEMPLATE_ID = 0x50e2; + + int num_pad_bytes (int len) + { + return ALIGNMENT_PADDING ? (4 - len % 4) % 4 : 0; + } + + QByteArray boundedUtf8 (QString const& value, int max_bytes) + { + auto utf8 = value.toUtf8 (); + if (utf8.size () <= max_bytes) + { + return utf8; + } + + auto bounded_size = qMax (0, max_bytes); + while (bounded_size > 0 + && (static_cast<quint8> (utf8[bounded_size]) & 0xc0) == 0x80) + { + --bounded_size; + } + return utf8.left (bounded_size); + } + + void writeUtfString (QDataStream& out, QString const& value, int max_bytes) + { + auto const utf8 = boundedUtf8 (value, max_bytes); + out << quint8 (utf8.size ()); + out.writeRawData (utf8.constData (), utf8.size ()); + } + + void setLength (QDataStream& out, QByteArray& bytes, int offset = sizeof (quint16)) + { + auto const pad_len = num_pad_bytes (bytes.size ()); + if (pad_len) + { + out.writeRawData (QByteArray {pad_len, '\0'}.constData (), pad_len); + } + + auto const pos = out.device ()->pos (); + out.device ()->seek (offset); + out << static_cast<quint16> (bytes.size ()); + out.device ()->seek (pos); + } + + QByteArray descriptorSets () + { + QByteArray sets; + { + // Sender Information template: callsign, frequency, SNR, mode, locator, + // information source, and spot timestamp. + QByteArray descriptor; + QDataStream out {&descriptor, QIODevice::WriteOnly}; + out + << quint16 (2u) + << quint16 (0u) + << quint16 (SENDER_TEMPLATE_ID) + << quint16 (7u) + << quint16 (0x8000 + 1u) // senderCallsign + << quint16 (0xffff) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 5u) // frequency, 5-byte unsigned integer + << quint16 (5u) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 6u) // sNR + << quint16 (1u) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 10u) // mode + << quint16 (0xffff) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 3u) // senderLocator + << quint16 (0xffff) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 11u) // informationSource + << quint16 (1u) + << PSK_REPORTER_PEN + << quint16 (150u) // dateTimeSeconds + << quint16 (4u); + setLength (out, descriptor); + sets.append (descriptor); + } + { + // Receiver Information options template. Scope Field Count must remain 1: + // receiverCallsign scopes receiver locator, software, antenna, and rig. + QByteArray descriptor; + QDataStream out {&descriptor, QIODevice::WriteOnly}; + out + << quint16 (3u) + << quint16 (0u) + << quint16 (RECEIVER_TEMPLATE_ID) + << quint16 (5u) + << quint16 (1u) + << quint16 (0x8000 + 2u) // receiverCallsign, scope field + << quint16 (0xffff) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 4u) // receiverLocator + << quint16 (0xffff) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 8u) // decodingSoftware + << quint16 (0xffff) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 9u) // antennaInformation + << quint16 (0xffff) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 13u) // rigInformation + << quint16 (0xffff) + << PSK_REPORTER_PEN; + setLength (out, descriptor); + sets.append (descriptor); + } + return sets; + } + + QByteArray receiverSet (PSKReporterIPFIX::Receiver const& receiver) + { + QByteArray data; + QDataStream out {&data, QIODevice::WriteOnly}; + out << quint16 (RECEIVER_TEMPLATE_ID) << quint16 (0u); + writeUtfString (out, receiver.callsign, CALLSIGN_LIMIT); + writeUtfString (out, receiver.locator, LOCATOR_LIMIT); + writeUtfString (out, receiver.program_info, PROGRAM_INFO_LIMIT); + writeUtfString (out, receiver.antenna, ANTENNA_LIMIT); + writeUtfString (out, receiver.rig_information, RIG_INFORMATION_LIMIT); + setLength (out, data); + return data; + } + + int senderSetLength (int record_bytes) + { + auto const len = 2 * sizeof (quint16) + record_bytes; + return len + num_pad_bytes (len); + } + + int messageLength (int set_bytes) + { + auto const len = 2 * sizeof (quint16) + 3 * sizeof (quint32) + set_bytes; + return len + num_pad_bytes (len); + } + + QByteArray spotRecord (PSKReporterIPFIX::Spot const& spot) + { + QByteArray data; + QDataStream out {&data, QIODevice::WriteOnly}; + // Field order must match the sender template above. + writeUtfString (out, spot.callsign, CALLSIGN_LIMIT); + + out + << static_cast<quint8> ((spot.frequency >> 32) & 0xff) + << static_cast<quint32> (spot.frequency & 0xffffffffu) + << static_cast<qint8> (spot.snr); + + writeUtfString (out, spot.mode, MODE_LIMIT); + writeUtfString (out, spot.locator, LOCATOR_LIMIT); + out + << quint8 (1u) + << static_cast<quint32> ( +#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0) + spot.time.toSecsSinceEpoch () +#else + spot.time.toMSecsSinceEpoch () / 1000 +#endif + ); + return data; + } + + QByteArray senderSet (QList<QByteArray> const& records) + { + QByteArray data; + QDataStream out {&data, QIODevice::WriteOnly}; + out << quint16 (SENDER_TEMPLATE_ID) << quint16 (0u); + for (auto const& record : records) + { + out.writeRawData (record.constData (), record.size ()); + } + setLength (out, data); + return data; + } + + QByteArray message (QByteArray const& sets, quint32 sequence_number, quint32 observation_id, quint32 export_time) + { + QByteArray data; + QDataStream out {&data, QIODevice::WriteOnly}; + out + << quint16 (10u) + << quint16 (0u) + << export_time + << sequence_number + << observation_id; + out.writeRawData (sets.constData (), sets.size ()); + setLength (out, data); + return data; + } +} + +namespace PSKReporterIPFIX +{ + int maxUdpIpfixPayloadBytes () + { + return MAX_UDP_IPFIX_PAYLOAD_BYTES; + } + + int maxTcpIpfixPayloadBytes () + { + return MAX_TCP_IPFIX_PAYLOAD_BYTES; + } + + QList<Packet> buildPackets (Receiver const& receiver, QList<Spot> const& spots + , bool include_descriptors, quint32 sequence_number + , quint32 observation_id, quint32 export_time + , int max_payload_bytes) + { + QList<Packet> packets; + QByteArray first_base_sets; + if (include_descriptors) + { + first_base_sets.append (descriptorSets ()); + } + auto const receiver_set = receiverSet (receiver); + first_base_sets.append (receiver_set); + + auto const base_payload = message (first_base_sets, sequence_number, observation_id, export_time); + Q_ASSERT (base_payload.size () <= max_payload_bytes); + if (spots.isEmpty ()) + { + packets.append ({base_payload, 0}); + return packets; + } + + QList<QByteArray> records; + int record_count = 0; + int record_bytes = 0; + auto base_sets = first_base_sets; + for (auto const& spot : spots) + { + auto const record = spotRecord (spot); + auto const candidate_record_bytes = record_bytes + record.size (); + auto const candidate_payload_size = messageLength (base_sets.size () + senderSetLength (candidate_record_bytes)); + if (!records.isEmpty () && candidate_payload_size > max_payload_bytes) + { + auto const payload = message (base_sets + senderSet (records), sequence_number, observation_id, export_time); + Q_ASSERT (payload.size () <= max_payload_bytes); + packets.append ({payload, record_count}); + sequence_number += record_count; + records.clear (); + record_count = 0; + record_bytes = 0; + // Follow-on split packets keep receiver data but do not repeat + // descriptors until the caller schedules the next descriptor send. + base_sets = receiver_set; + } + + records.append (record); + ++record_count; + record_bytes += record.size (); + Q_ASSERT (messageLength (base_sets.size () + senderSetLength (record_bytes)) <= max_payload_bytes); + } + + if (!records.isEmpty ()) + { + auto const payload = message (base_sets + senderSet (records), sequence_number, observation_id, export_time); + Q_ASSERT (payload.size () <= max_payload_bytes); + packets.append ({payload, record_count}); + } + + return packets; + } +} diff --git a/Network/PSKReporterIPFIX.hpp b/Network/PSKReporterIPFIX.hpp new file mode 100644 index 00000000..1704f6fa --- /dev/null +++ b/Network/PSKReporterIPFIX.hpp @@ -0,0 +1,47 @@ +#ifndef PSK_REPORTER_IPFIX_HPP_ +#define PSK_REPORTER_IPFIX_HPP_ + +#include <QByteArray> +#include <QDateTime> +#include <QList> +#include <QString> + +#include "Radio.hpp" + +namespace PSKReporterIPFIX +{ + int maxUdpIpfixPayloadBytes (); + int maxTcpIpfixPayloadBytes (); + + struct Receiver + { + QString callsign; + QString locator; + QString program_info; + QString antenna; + QString rig_information; + }; + + struct Spot + { + QString callsign; + QString locator; + int snr; + Radio::Frequency frequency; + QString mode; + QDateTime time; + }; + + struct Packet + { + QByteArray payload; + int spot_count; + }; + + QList<Packet> buildPackets (Receiver const& receiver, QList<Spot> const& spots + , bool include_descriptors, quint32 sequence_number + , quint32 observation_id, quint32 export_time + , int max_payload_bytes); +} + +#endif 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 |
