diff options
| author | Christoph Berg <myon@debian.org> | 2026-06-22 12:03:44 +0200 |
|---|---|---|
| committer | Christoph Berg <myon@debian.org> | 2026-06-22 12:03:44 +0200 |
| commit | d83a420f0517d7fc47aeb288a6a0cf4891784fcc (patch) | |
| tree | 6d9c83527c56458a8360ba080bf5f4ca73d526dc /Network | |
| parent | 4b089ae3f7e9e2d5662f718f663b26a4e8ee63ca (diff) | |
New upstream version 3.0.2+dfsgupstream/3.0.2+dfsg
Diffstat (limited to 'Network')
| -rw-r--r-- | Network/Cloudlog.cpp | 4 | ||||
| -rw-r--r-- | Network/PSKReporter.cpp | 524 | ||||
| -rw-r--r-- | Network/PSKReporter.hpp | 14 | ||||
| -rw-r--r-- | Network/PSKReporterConfiguration.cpp | 18 | ||||
| -rw-r--r-- | Network/PSKReporterIPFIX.cpp | 294 | ||||
| -rw-r--r-- | Network/PSKReporterIPFIX.hpp | 47 |
6 files changed, 504 insertions, 397 deletions
diff --git a/Network/Cloudlog.cpp b/Network/Cloudlog.cpp index ea9ac395..50e2fdee 100644 --- a/Network/Cloudlog.cpp +++ b/Network/Cloudlog.cpp @@ -26,6 +26,7 @@ #include "moc_Cloudlog.cpp" #include "Configuration.hpp" +#include "revision_utils.hpp" namespace { @@ -63,6 +64,7 @@ public: QNetworkRequest request(u); request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json")); + request.setRawHeader ("User-Agent", http_user_agent ().toUtf8 ()); reply_ = network_manager_->post(request, data); connect (reply_.data (), &QNetworkReply::finished, this, &Cloudlog::impl::reply_logqso); @@ -89,7 +91,7 @@ public: } QNetworkRequest request {apiUrl+"/index.php/api/auth/"+apiKey}; - request.setRawHeader ("User-Agent", "WSJT-X Cloudlog API"); + request.setRawHeader ("User-Agent", http_user_agent ().toUtf8 ()); request.setOriginatingObject (this); reply_ = network_manager_->get (request); connect (reply_.data (), &QNetworkReply::finished, this, &Cloudlog::impl::reply_apitest); diff --git a/Network/PSKReporter.cpp b/Network/PSKReporter.cpp index 5e64d5c5..5a0eac26 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" @@ -42,15 +38,15 @@ namespace // 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 +56,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 +73,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 +82,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 +118,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 +139,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) @@ -174,11 +163,11 @@ public: // use this for pseudo connection with UDP, allows us to use // QIODevice::write() instead of QUDPSocket::writeDatagram() socket_->connectToHost (HOST, SERVICE_PORT, QAbstractSocket::WriteOnly); - LOG_LOG_LOCATION (logger_, debug, "remote host: " << HOST << " port: " << SERVICE_PORT); + LOG_LOG_LOCATION (logger_, debug, "remote host: " << HOST.latin1 () << " port: " << SERVICE_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 +187,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 +197,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 +351,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 +366,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..46fe0a82 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,22 @@ class PSKReporter final Q_OBJECT public: + struct Options + { + bool use_tcpip; + QString eclipse_file_path; + QString program_info; + }; + 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 |
