Security hardening: fix 19 of 22 vulnerabilities found in audit

Critical:
- Trunk HMAC-SHA1 auth: MsgTrunkHello now carries nonce+digest,
  peer disconnected on secret mismatch (was loaded but never verified)

High:
- Pre-hello guard: reject all trunk messages before handshake completes
- CSPRNG for password generator: random.choice -> secrets.choice

Medium:
- Path traversal protection on callsign-based file operations
- Replace assert() on network-derived UDP data with error handling
- HTTP server connection throttling (matching main TCP server)
- try/catch on regex compilation in callsignOk()/emailOk()
- Per-link trunk talker tracking (clearAllTrunkTalkers scoped to peer)
- Regenerate priority nonce on each new trunk connection
- Cap active TGs and trunk talkers at 10000 each
- Don't reset heartbeat for unauthenticated client app messages
- Fix RENEW_AFTER integer division (2/3 -> 2.0/3.0)

Low:
- JSON-escape HTTP method in error response
- snprintf for pidfile error message
- MsgAuthResponse::digest() null check on empty vector
- Check unpack() return values in AsyncMsg.h vector/map/string
- Replace stack VLA with std::string; reserve+push_back vs resize
- Require TalkerStart before accepting trunk audio
This commit is contained in:
Audric committed 2026-03-20 11:54:18 +01:00
commit fca7c33794
276 files changed
+73533

No files matched your search

+1
View File
@@ -0,0 +1 @@
add_subdirectory(reflector)
+55
View File
@@ -0,0 +1,55 @@
# Find the popt library
find_package(Popt REQUIRED)
set(LIBS ${LIBS} ${POPT_LIBRARIES})
include_directories(${POPT_INCLUDE_DIRS})
add_definitions(${POPT_DEFINITIONS})
# Find the GCrypt library
#find_package(GCrypt REQUIRED)
#set(LIBS ${LIBS} ${GCRYPT_LIBRARIES})
#include_directories(${GCRYPT_INCLUDE_DIRS})
#add_definitions(${GCRYPT_DEFINITIONS})
# Find jsoncpp library
#find_package(jsoncpp REQUIRED)
#get_target_property(JSONCPP_INC_PATH jsoncpp_lib INTERFACE_INCLUDE_DIRECTORIES)
#include_directories(${JSONCPP_INC_PATH})
#set(LIBS ${LIBS} jsoncpp_lib)
pkg_check_modules (JSONCPP REQUIRED jsoncpp)
include_directories(${JSONCPP_INCLUDE_DIRS})
set(LIBS ${LIBS} ${JSONCPP_LIBRARIES})
# Add project libraries
set(LIBS asynccpp asyncaudio asynccore svxmisc ${LIBS})
# Build the executable
add_executable(svxreflector
svxreflector.cpp Reflector.cpp ReflectorClient.cpp TGHandler.cpp TrunkLink.cpp
)
target_link_libraries(svxreflector ${LIBS})
set_target_properties(svxreflector PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${RUNTIME_OUTPUT_DIRECTORY}
)
# Generate config file with correct paths
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/svxreflector.conf.in
${CMAKE_CURRENT_BINARY_DIR}/svxreflector.conf
@ONLY
)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/ca-hook.py.in
${CMAKE_CURRENT_BINARY_DIR}/ca-hook.py
@ONLY
)
# Install targets
install(TARGETS svxreflector DESTINATION ${BIN_INSTALL_DIR})
install_if_not_exists(${CMAKE_CURRENT_BINARY_DIR}/svxreflector.conf
${SVX_SYSCONF_INSTALL_DIR}
)
install_if_not_exists(ca-hook.yaml ${SVX_SYSCONF_INSTALL_DIR})
install(PROGRAMS svxreflector-status
DESTINATION ${BIN_INSTALL_DIR}
)
install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/ca-hook.py
DESTINATION ${SVX_SHARE_INSTALL_DIR}
)
+215
View File
@@ -0,0 +1,215 @@
/**
@file ProtoVer.h
@brief A couple of classes for doing protocol version manipulations
@author Tobias Blomberg / SM0SVX
@date 2019-07-25
\verbatim
SvxReflector - An audio reflector for connecting SvxLink Servers
Copyright (C) 2003-2019 Tobias Blomberg / SM0SVX
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\endverbatim
*/
#ifndef PROTO_VER_INCLUDED
#define PROTO_VER_INCLUDED
/****************************************************************************
*
* System Includes
*
****************************************************************************/
#include <limits>
/****************************************************************************
*
* Project Includes
*
****************************************************************************/
/****************************************************************************
*
* Local Includes
*
****************************************************************************/
/****************************************************************************
*
* Forward declarations
*
****************************************************************************/
/****************************************************************************
*
* Namespace
*
****************************************************************************/
//namespace MyNameSpace
//{
/****************************************************************************
*
* Forward declarations of classes inside of the declared namespace
*
****************************************************************************/
/****************************************************************************
*
* Defines & typedefs
*
****************************************************************************/
/****************************************************************************
*
* Exported Global Variables
*
****************************************************************************/
/****************************************************************************
*
* Class definitions
*
****************************************************************************/
/**
@brief A class for doing protocol version manipulations
@author Tobias Blomberg / SM0SVX
@date 2019-07-25
This class is used to represent a protocol version and to compare one version
to another.
*/
class ProtoVer
{
public:
static ProtoVer max(void)
{
return ProtoVer(
std::numeric_limits<uint16_t>::max(),
std::numeric_limits<uint16_t>::max());
}
/**
* @brief Default constructor
*/
ProtoVer(void) : m_major_ver(0), m_minor_ver(0) {}
ProtoVer(uint16_t major_ver, uint16_t minor_ver)
: m_major_ver(major_ver), m_minor_ver(minor_ver) {}
void set(uint16_t major_ver, uint16_t minor_ver)
{
m_major_ver = major_ver;
m_minor_ver = minor_ver;
}
uint16_t majorVer(void) const { return m_major_ver; }
uint16_t minorVer(void) const { return m_minor_ver; }
bool isValid(void) const { return (m_major_ver > 0) || (m_minor_ver > 0); }
bool operator ==(const ProtoVer& rhs) const
{
return (m_major_ver == rhs.m_major_ver) &&
(m_minor_ver == rhs.m_minor_ver);
}
bool operator !=(const ProtoVer& rhs) const
{
return !(m_major_ver == rhs.m_major_ver);
}
bool operator <(const ProtoVer& rhs) const
{
return (m_major_ver < rhs.m_major_ver) ||
((m_major_ver == rhs.m_major_ver) &&
(m_minor_ver < rhs.m_minor_ver));
}
bool operator >(const ProtoVer& rhs) const
{
return (m_major_ver > rhs.m_major_ver) ||
((m_major_ver == rhs.m_major_ver) &&
(m_minor_ver > rhs.m_minor_ver));
}
bool operator <=(const ProtoVer& rhs) const
{
return (*this == rhs) || (*this < rhs);
}
bool operator >=(const ProtoVer& rhs) const
{
return (*this == rhs) || (*this > rhs);
}
/**
* @brief A_brief_member_function_description
* @param param1 Description_of_param1
* @return Return_value_of_this_member_function
*/
private:
uint16_t m_major_ver;
uint16_t m_minor_ver;
}; /* class ProtoVer */
/**
@brief A class for doing protocol version manipulations on ranges
@author Tobias Blomberg / SM0SVX
@date 2019-07-25
This class is used to represent a protocol version range and to check if a
version is within that range.
*/
class ProtoVerRange
{
public:
ProtoVerRange(void) {}
ProtoVerRange(const ProtoVer& min, const ProtoVer& max)
: m_min(min), m_max(max)
{
}
bool isValid(void) const { return m_min.isValid() && m_max.isValid(); }
bool isWithinRange(const ProtoVer& ver) const
{
return (ver >= m_min) && (ver <= m_max);
}
private:
ProtoVer m_min;
ProtoVer m_max;
}; /* class ProtoVerRange */
//} /* namespace */
#endif /* PROTO_VER_INCLUDED */
/*
* This file has not been truncated
*/
File diff suppressed because it is too large. Load diff
+331
View File
@@ -0,0 +1,331 @@
/**
@file Reflector.h
@brief The main reflector class
@author Tobias Blomberg / SM0SVX
@date 2017-02-11
\verbatim
SvxReflector - An audio reflector for connecting SvxLink Servers
Copyright (C) 2003-2026 Tobias Blomberg / SM0SVX
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\endverbatim
*/
#ifndef REFLECTOR_INCLUDED
#define REFLECTOR_INCLUDED
/****************************************************************************
*
* System Includes
*
****************************************************************************/
#include <sigc++/sigc++.h>
#include <sys/time.h>
#include <vector>
#include <string>
#include <json/json.h>
/****************************************************************************
*
* Project Includes
*
****************************************************************************/
#include <AsyncTcpServer.h>
#include <AsyncFramedTcpConnection.h>
#include <AsyncTimer.h>
#include <AsyncAtTimer.h>
#include <AsyncHttpServerConnection.h>
#include <AsyncExec.h>
/****************************************************************************
*
* Local Includes
*
****************************************************************************/
#include "ProtoVer.h"
#include "ReflectorClient.h"
#include "TrunkLink.h"
/****************************************************************************
*
* Forward declarations
*
****************************************************************************/
namespace Async
{
class EncryptedUdpSocket;
class Config;
class Pty;
};
class ReflectorMsg;
class ReflectorUdpMsg;
/****************************************************************************
*
* Forward declarations of classes inside of the declared namespace
*
****************************************************************************/
/****************************************************************************
*
* Defines & typedefs
*
****************************************************************************/
/**
* @brief Structure to hold certificate or CSR information
*
* - Signed certificates (is_signed=true, has valid_until/not_after)
* - Pending CSRs (is_signed=false, has received_time)
*/
struct CertInfo
{
std::string callsign; // Common Name
std::vector<std::string> emails; // Email addresses from SAN
bool is_signed; // true=signed cert, false=pending CSR
// For signed certificates:
std::string valid_until; // Human-readable expiry date
time_t not_after; // Unix timestamp for expiry (0 if pending)
// For pending CSRs:
time_t received_time; // Unix timestamp when CSR received (0 if cert)
CertInfo() : is_signed(false), not_after(0), received_time(0) {}
};
/****************************************************************************
*
* Exported Global Variables
*
****************************************************************************/
/****************************************************************************
*
* Class definitions
*
****************************************************************************/
/**
@brief The main reflector class
@author Tobias Blomberg / SM0SVX
@date 2017-02-11
This is the main class for the reflector. It handles all network traffic and
the dispatching of incoming messages to the correct ReflectorClient object.
*/
class Reflector : public sigc::trackable
{
public:
static time_t timeToRenewCert(const Async::SslX509& cert);
/**
* @brief Default constructor
*/
Reflector(void);
/**
* @brief Destructor
*/
~Reflector(void);
/**
* @brief Initialize the reflector
* @param cfg A previously initialized configuration object
* @return Return \em true on success or else \em false
*/
bool initialize(Async::Config &cfg);
/**
* @brief Return a list of all connected nodes
* @param nodes The vector to return the result in
*
* This function is used to get a list of the callsigns of all connected
* nodes.
*/
void nodeList(std::vector<std::string>& nodes) const;
/**
* @brief Broadcast a TCP message to connected clients
* @param msg The message to broadcast
* @param filter The client filter to apply
*
* This function is used to broadcast a message to all connected clients,
* possibly applying a client filter. The message is not really a IP
* broadcast but rather unicast to all connected clients.
*/
void broadcastMsg(const ReflectorMsg& msg,
const ReflectorClient::Filter& filter=ReflectorClient::NoFilter());
/**
* @brief Send a UDP datagram to the specificed ReflectorClient
* @param client The client to the send datagram to
* @param buf The payload to send
* @param count The number of bytes in the payload
* @return Returns \em true on success or else \em false
*/
bool sendUdpDatagram(ReflectorClient *client, const ReflectorUdpMsg& msg);
void broadcastUdpMsg(const ReflectorUdpMsg& msg,
const ReflectorClient::Filter& filter=ReflectorClient::NoFilter());
/**
* @brief Get the TG for protocol V1 clients
* @return Returns the TG used for protocol V1 clients
*/
uint32_t tgForV1Clients(void) { return m_tg_for_v1_clients; }
/**
* @brief Request QSY to another talk group
* @param tg The talk group to QSY to
*/
void requestQsy(ReflectorClient *client, uint32_t tg);
Async::EncryptedUdpSocket* udpSocket(void) const { return m_udp_sock; }
uint32_t randomQsyLo(void) const { return m_random_qsy_lo; }
uint32_t randomQsyHi(void) const { return m_random_qsy_hi; }
Async::SslCertSigningReq loadClientPendingCsr(const std::string& callsign);
Async::SslCertSigningReq loadClientCsr(const std::string& callsign);
bool renewedClientCert(Async::SslX509& cert);
bool signClientCert(Async::SslX509& cert, const std::string& ca_op);
Async::SslX509 signClientCsr(const std::string& cn);
Async::SslX509 loadClientCertificate(const std::string& callsign);
size_t caSize(void) const { return m_ca_size; }
const std::vector<uint8_t>& caDigest(void) const { return m_ca_md; }
const std::vector<uint8_t>& caSignature(void) const { return m_ca_sig; }
std::string clientCertPem(const std::string& callsign) const;
std::string caBundlePem(void) const;
std::string issuingCertPem(void) const;
bool callsignOk(const std::string& callsign, bool verbose=true) const;
bool reqEmailOk(const Async::SslCertSigningReq& req) const;
bool emailOk(const std::string& email) const;
std::string checkCsr(const Async::SslCertSigningReq& req);
Async::SslX509 csrReceived(Async::SslCertSigningReq& req);
Json::Value& clientStatus(const std::string& callsign);
protected:
private:
typedef std::map<Async::FramedTcpConnection*,
ReflectorClient*> ReflectorClientConMap;
typedef Async::TcpServer<Async::FramedTcpConnection> FramedTcpServer;
using HttpServer = Async::TcpServer<Async::HttpServerConnection>;
static constexpr unsigned ROOT_CA_VALIDITY_DAYS = 25*365;
static constexpr unsigned ISSUING_CA_VALIDITY_DAYS = 4*90;
static constexpr unsigned CERT_VALIDITY_DAYS = 90;
static constexpr int CERT_VALIDITY_OFFSET_DAYS = -1;
FramedTcpServer* m_srv;
Async::EncryptedUdpSocket* m_udp_sock;
ReflectorClientConMap m_client_con_map;
Async::Config* m_cfg;
uint32_t m_tg_for_v1_clients;
uint32_t m_random_qsy_lo;
uint32_t m_random_qsy_hi;
uint32_t m_random_qsy_tg;
HttpServer* m_http_server;
Async::Pty* m_cmd_pty;
Async::SslContext m_ssl_ctx;
std::string m_keys_dir;
std::string m_pending_csrs_dir;
std::string m_csrs_dir;
std::string m_certs_dir;
UdpCipher::AAD m_aad;
Async::SslKeypair m_ca_pkey;
Async::SslX509 m_ca_cert;
Async::SslKeypair m_issue_ca_pkey;
Async::SslX509 m_issue_ca_cert;
std::string m_pki_dir;
std::string m_ca_bundle_file;
std::string m_crtfile;
Async::AtTimer m_renew_cert_timer;
Async::AtTimer m_renew_issue_ca_cert_timer;
size_t m_ca_size = 0;
std::vector<uint8_t> m_ca_md;
std::vector<uint8_t> m_ca_sig;
std::string m_accept_cert_email;
Json::Value m_status;
std::vector<TrunkLink*> m_trunk_links;
Reflector(const Reflector&);
Reflector& operator=(const Reflector&);
void clientConnected(Async::FramedTcpConnection *con);
void clientDisconnected(Async::FramedTcpConnection *con,
Async::FramedTcpConnection::DisconnectReason reason);
bool udpCipherDataReceived(const Async::IpAddress& addr, uint16_t port,
void *buf, int count);
void udpDatagramReceived(const Async::IpAddress& addr, uint16_t port,
void* aad, void *buf, int count);
void onTalkerUpdated(uint32_t tg, ReflectorClient* old_talker,
ReflectorClient *new_talker);
void httpRequestReceived(Async::HttpServerConnection *con,
Async::HttpServerConnection::Request& req);
void httpClientConnected(Async::HttpServerConnection *con);
void httpClientDisconnected(Async::HttpServerConnection *con,
Async::HttpServerConnection::DisconnectReason reason);
void onRequestAutoQsy(uint32_t from_tg);
uint32_t nextRandomQsyTg(void);
void ctrlPtyDataReceived(const void *buf, size_t count);
void cfgUpdated(const std::string& section, const std::string& tag);
void onTrunkTalkerUpdated(uint32_t tg, std::string old_cs,
std::string new_cs);
void initTrunkLinks(void);
bool loadCertificateFiles(void);
bool loadServerCertificateFiles(void);
bool generateKeyFile(Async::SslKeypair& pkey, const std::string& keyfile);
bool loadRootCAFiles(void);
bool loadSigningCAFiles(void);
bool onVerifyPeer(Async::TcpConnection *con, bool preverify_ok,
X509_STORE_CTX *x509_store_ctx);
bool buildPath(const std::string& sec, const std::string& tag,
const std::string& defdir, std::string& defpath);
bool removeClientCertFiles(const std::string& cn);
void runCAHook(const Async::Exec::Environment& env);
std::vector<CertInfo> getAllCerts(void);
std::vector<CertInfo> getAllPendingCSRs(void);
std::string formatCerts(bool signedCerts=true, bool pendingCerts=true);
}; /* class Reflector */
#endif /* REFLECTOR_INCLUDED */
/*
* This file has not been truncated
*/
File diff suppressed because it is too large. Load diff
+616
View File
@@ -0,0 +1,616 @@
/**
@file ReflectorClient.h
@brief Represents one client connection
@author Tobias Blomberg / SM0SVX
@date 2017-02-11
\verbatim
SvxReflector - An audio reflector for connecting SvxLink Servers
Copyright (C) 2003-2025 Tobias Blomberg / SM0SVX
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\endverbatim
*/
#ifndef REFLECTOR_CLIENT_INCLUDED
#define REFLECTOR_CLIENT_INCLUDED
/****************************************************************************
*
* System Includes
*
****************************************************************************/
#include <string>
#include <json/json.h>
#include <sigc++/sigc++.h>
#include <random>
/****************************************************************************
*
* Project Includes
*
****************************************************************************/
#include <AsyncFramedTcpConnection.h>
#include <AsyncTimer.h>
#include <AsyncAtTimer.h>
#include <AsyncConfig.h>
#include <AsyncSslCertSigningReq.h>
#include <AsyncSslX509.h>
/****************************************************************************
*
* Local Includes
*
****************************************************************************/
#include "ReflectorMsg.h"
#include "ProtoVer.h"
/****************************************************************************
*
* Forward declarations
*
****************************************************************************/
/****************************************************************************
*
* Forward declarations of classes inside of the declared namespace
*
****************************************************************************/
class Reflector;
/****************************************************************************
*
* Defines & typedefs
*
****************************************************************************/
/****************************************************************************
*
* Exported Global Variables
*
****************************************************************************/
/****************************************************************************
*
* Class definitions
*
****************************************************************************/
/**
@brief Represents one client connection
@author Tobias Blomberg / SM0SVX
@date 2017-02-11
This class represents one client connection. When a client connects, an
instance of this class will be created that will persist for the lifetime of
the client connection.
*/
class ReflectorClient : public sigc::trackable
{
public:
using ClientId = ReflectorUdpMsg::ClientId;
using ClientSrc = std::pair<Async::IpAddress, uint16_t>;
typedef enum
{
STATE_EXPECT_DISCONNECT,
STATE_DISCONNECTED,
STATE_EXPECT_PROTO_VER,
STATE_EXPECT_START_ENCRYPTION,
STATE_EXPECT_SSL_CON_READY,
STATE_EXPECT_CSR,
STATE_EXPECT_AUTH_RESPONSE,
STATE_CONNECTED
} ConState;
class Filter
{
public:
virtual ~Filter(void) {}
virtual bool operator ()(ReflectorClient *client) const = 0;
};
class NoFilter : public Filter
{
public:
virtual bool operator ()(ReflectorClient *) const { return true; }
};
class ExceptFilter : public Filter
{
public:
ExceptFilter(const ReflectorClient* except) : m_except(except) {}
virtual bool operator ()(ReflectorClient *client) const
{
return client != m_except;
}
private:
const ReflectorClient* m_except;
};
class ProtoVerRangeFilter : public Filter
{
public:
ProtoVerRangeFilter(const ProtoVerRange& pvr) : m_pv_range(pvr) {}
ProtoVerRangeFilter(const ProtoVer& min, const ProtoVer& max)
: m_pv_range(min, max) {}
virtual bool operator ()(ReflectorClient *client) const
{
return (!m_pv_range.isValid() ||
m_pv_range.isWithinRange(client->protoVer()));
}
private:
ProtoVerRange m_pv_range;
};
class ProtoVerLargerOrEqualFilter : public Filter
{
public:
ProtoVerLargerOrEqualFilter(const ProtoVer& min) : m_pv(min) {}
virtual bool operator ()(ReflectorClient *client) const
{
return (client->protoVer() >= m_pv);
}
private:
ProtoVer m_pv;
};
class TgFilter : public Filter
{
public:
TgFilter(uint32_t tg) : m_tg(tg) {}
virtual bool operator ()(ReflectorClient *client) const;
private:
uint32_t m_tg;
};
class TgMonitorFilter : public Filter
{
public:
TgMonitorFilter(uint32_t tg) : m_tg(tg) {}
virtual bool operator ()(ReflectorClient *client) const
{
return client->m_monitored_tgs.count(m_tg) > 0;
}
private:
uint32_t m_tg;
};
template <class F1, class F2>
class AndFilter : public Filter
{
public:
AndFilter(const F1& f1, const F2& f2) : m_f1(f1), m_f2(f2) {}
virtual bool operator ()(ReflectorClient *client) const
{
return m_f1(client) && m_f2(client);
}
private:
F1 m_f1;
F2 m_f2;
};
template <class F1, class F2>
static AndFilter<F1, F2> mkAndFilter(const F1& f1, const F2& f2)
{
return AndFilter<F1, F2>(f1, f2);
}
template <class F1, class F2>
class OrFilter : public Filter
{
public:
OrFilter(const F1& f1, const F2& f2) : m_f1(f1), m_f2(f2) {}
virtual bool operator ()(ReflectorClient *client) const
{
return m_f1(client) || m_f2(client);
}
private:
F1 m_f1;
F2 m_f2;
};
template <class F1, class F2>
static OrFilter<F1, F2> mkOrFilter(const F1& f1, const F2& f2)
{
return OrFilter<F1, F2>(f1, f2);
}
/**
* @brief Get the client object associated with the given id
* @param id The id of the client object to find
* @return Return the client object associated with the given id
*/
static ReflectorClient* lookup(const ClientId& id);
/**
* @brief Get the client object associated with the given source addr
* @param src The source address of the client object to find
* @return Return the client object associated with the given source addr
*/
static ReflectorClient* lookup(const ClientSrc& src);
/**
* @brief Get the client object associated with the given callsign
* @param cs The callsign of the client object to find
* @return Return the client object associated with the given callsign
*/
static ReflectorClient* lookup(const std::string& cs);
/**
* @brief Remove all client objects
*/
static void cleanup(void);
/**
* @brief Constructor
* @param ref The associated Reflector object
* @param con The associated FramedTcpConnection object
* @param cfg The associated configuration file object
*/
ReflectorClient(Reflector *ref, Async::FramedTcpConnection *con,
Async::Config* cfg);
/**
* @brief Destructor
*/
~ReflectorClient(void);
/**
* @brief Return the client ID
* @return Returns the client ID
*
* The client ID is a unique number assigned to each connected client.
* It is for example used to associate incoming audio with the correct
* client.
*/
ClientId clientId(void) const { return m_client_id; }
/**
* @brief Get the local IP address associated with this connection
* @return Returns an IP address
*/
Async::IpAddress localHost(void) const
{
return m_con->localHost();
}
/**
* @brief Get the local TCP port associated with this connection
* @return Returns a port number
*/
uint16_t localPort(void) const
{
return m_con->localPort();
}
/**
* @brief Return the remote IP address
* @return Returns the IP address of the client
*/
const Async::IpAddress& remoteHost(void) const
{
return m_con->remoteHost();
}
uint16_t remotePort(void) const
{
return m_con->remotePort();
}
/**
* @brief Return the remote UDP IP
* @return Returns the source IP used by the client for UDP
*/
const Async::IpAddress& remoteUdpHost(void) const
{
const auto& addr = m_client_src.first;
if (addr.isEmpty())
{
return remoteHost();
}
return addr;
}
/**
* @brief Return the remote port number
* @return Returns the source port used by the client for UDP
*/
uint16_t remoteUdpPort(void) const { return m_remote_udp_port; }
/**
* @brief Set the remote UDP source (IP, port)
* @param src A ClientSrc
*
* The Reflector use this function to set the (IP, port number) used by the
* client so that UDP packets can be sent to the client, incoming UDP
* packets can be associated with the correct client object and to check
* that incoming packets originate from the correct source.
*/
void setRemoteUdpSource(const ClientSrc& src);
/**
* @brief Get the callsign for this connection
* @return Returns the callsign associated with this coinnection
*/
const std::string& callsign(void) const { return m_callsign; }
/**
* @brief Return the next UDP packet transmit sequence number
* @return Returns the UDP packet sequence number that should be used next
*
* This function will return the UDP packet sequence number that should be
* used next. The squence number is incremented when this function is called
* so it can only be called one time per packet. The sequence number is
* used by the receiver to find out if a packet is out of order or if a
* packet has been lost in transit.
*/
//uint16_t nextUdpTxSeq(void) { return m_next_udp_tx_seq++; }
/**
* @brief Set the UDP RX sequence number
*/
void setUdpRxSeq(UdpCipher::IVCntr seq) { m_next_udp_rx_seq = seq; }
/**
* @brief Get the next expected UDP packet sequence number
* @return Returns the next expected UDP packet sequence number
*
* This function will return the next expected UDP sequence number, which
* is simply the previously received sequence number plus one.
*/
UdpCipher::IVCntr nextUdpRxSeq(void) { return m_next_udp_rx_seq; }
/**
* @brief Send a TCP message to the remote end
* @param The mesage to send
* @return On success 0 is returned or else -1
*/
int sendMsg(const ReflectorMsg& msg);
/**
* @brief Handle a received UDP message
* @param The received UDP message
*
* This function is called by the Reflector when a UDP packet is received.
* The purpose is to handle packet related timers and sequence numbers.
*/
void udpMsgReceived(const ReflectorUdpMsg &header);
/**
* @brief Send a UDP message to the client
* @param The message to send
*/
void sendUdpMsg(const ReflectorUdpMsg &msg);
/**
* @brief Block client audio for the specified time
* @param The number of seconds to block
*
* This function is used to block the client from sending audio for the
* specified time. This is used by the Reflector if a client has been
* talking for too long.
*/
void setBlock(unsigned blocktime);
/**
* @brief Check if a client is blocked
* @return Returns \em true if the client is blocked or else \em false
*/
bool isBlocked(void) const { return (m_remaining_blocktime > 0); }
/**
* @brief Get the state of the connection
* @return Returns the state of the connection
*/
ConState conState(void) const { return m_con_state; }
/**
* @brief Get the protocol version of the client
* @return Returns the protocol version of the client
*/
const ProtoVer& protoVer(void) const { return m_client_proto_ver; }
/**
* @brief Get the current talk group
* @return Returns the currently selected talk group
*/
uint32_t currentTG(void) const { return m_current_tg; }
/**
* @brief Get the monitored talk groups
* @return Returns the monitored talk groups
*/
const std::set<uint32_t>& monitoredTGs(void) const
{
return m_monitored_tgs;
}
std::vector<char> rxIdList(void) const
{
std::vector<char> ids;
ids.reserve(m_json_rx_map.size());
for (const auto& rx : m_json_rx_map)
{
ids.push_back(rx.first);
}
return ids;
}
void setRxSiglev(char id, uint8_t siglev)
{
setRxParam(id, "siglev", siglev);
}
void setRxEnabled(char id, bool enab) { setRxParam(id, "enabled", enab); }
void setRxSqlOpen(char id, bool open) { setRxParam(id, "sql_open", open); }
void setRxActive(char id, bool active) { setRxParam(id, "active", active); }
void setTxTransmit(char id, bool transmit)
{
setTxParam(id, "transmit", transmit);
}
void updateIsTalker(void);
uint32_t udpCipherIVCntrNext() { return m_udp_cipher_iv_cntr++; }
std::vector<uint8_t> udpCipherIV(void) const;
void setUdpCipherIVRand(const std::vector<uint8_t>& iv_rand)
{
m_udp_cipher_iv_rand = iv_rand;
}
std::vector<uint8_t> udpCipherIVRand(void) const
{
return m_udp_cipher_iv_rand;
}
void setUdpCipherKey(const std::vector<uint8_t>& key)
{
m_udp_cipher_key = key;
}
std::vector<uint8_t> udpCipherKey(void) const { return m_udp_cipher_key; }
void certificateUpdated(Async::SslX509& cert);
private:
using ClientIdRandomDist = std::uniform_int_distribution<ClientId>;
using ClientMap = std::map<ClientId, ReflectorClient*>;
using ClientSrcMap = std::map<ClientSrc, ReflectorClient*>;
using ClientCallsignMap = std::map<std::string, ReflectorClient*>;
using JsonRxMap = std::map<char, Json::Value&>;
using JsonTxMap = std::map<char, Json::Value&>;
static const uint16_t MIN_MAJOR_VER = 0;
static const uint16_t MIN_MINOR_VER = 6;
static const unsigned HEARTBEAT_TX_CNT_RESET = 10;
static const unsigned HEARTBEAT_RX_CNT_RESET = 15;
static const unsigned UDP_HEARTBEAT_TX_CNT_RESET = 15;
static const unsigned UDP_HEARTBEAT_RX_CNT_RESET = 120;
static const ClientId CLIENT_ID_MAX = std::numeric_limits<ClientId>::max();
static const ClientId CLIENT_ID_MIN = 1;
static ClientMap client_map;
static ClientSrcMap client_src_map;
static ClientCallsignMap client_callsign_map;
static std::mt19937 id_gen;
static ClientIdRandomDist id_dist;
Async::FramedTcpConnection* m_con;
unsigned char m_auth_challenge[MsgAuthChallenge::LENGTH];
ConState m_con_state;
Async::Timer m_disc_timer;
std::string m_callsign;
ClientId m_client_id;
ClientSrc m_client_src;
uint16_t m_remote_udp_port;
Async::Config* m_cfg;
UdpCipher::IVCntr m_next_udp_rx_seq;
Async::Timer m_heartbeat_timer;
unsigned m_heartbeat_tx_cnt;
unsigned m_heartbeat_rx_cnt;
unsigned m_udp_heartbeat_tx_cnt;
unsigned m_udp_heartbeat_rx_cnt;
Reflector* m_reflector;
unsigned m_blocktime;
unsigned m_remaining_blocktime;
ProtoVer m_client_proto_ver;
std::vector<std::string> m_supported_codecs;
uint32_t m_current_tg;
std::set<uint32_t> m_monitored_tgs;
JsonRxMap m_json_rx_map;
JsonTxMap m_json_tx_map;
std::vector<uint8_t> m_udp_cipher_iv_rand;
std::vector<uint8_t> m_udp_cipher_key;
UdpCipher::IVCntr m_udp_cipher_iv_cntr;
Async::AtTimer m_renew_cert_timer;
Json::Value* m_status {nullptr};
static ClientId newClientId(ReflectorClient* client);
ReflectorClient(const ReflectorClient&);
ReflectorClient& operator=(const ReflectorClient&);
void onSslConnectionReady(Async::TcpConnection *con);
void onFrameReceived(Async::FramedTcpConnection *con,
std::vector<uint8_t>& data);
void handleMsgProtoVer(std::istream& is);
void handleMsgCABundleRequest(std::istream& is);
void handleMsgStartEncryptionRequest(std::istream& is);
void handleMsgAuthResponse(std::istream& is);
void handleMsgClientCsr(std::istream& is);
void handleSelectTG(std::istream& is);
void handleTgMonitor(std::istream& is);
void handleNodeInfo(std::istream& is);
void handleMsgSignalStrengthValues(std::istream& is);
void handleMsgTxStatus(std::istream& is);
void handleRequestQsy(std::istream& is);
void handleStateEvent(std::istream& is);
void handleMsgError(std::istream& is);
void sendError(const std::string& msg);
void onDiscTimeout(Async::Timer *t);
void disconnect(void);
void handleHeartbeat(Async::Timer *t);
std::string lookupUserKey(const std::string& callsign);
void connectionAuthenticated(const std::string& callsign);
bool sendClientCert(const Async::SslX509& cert);
void sendAuthChallenge(void);
void renewClientCertificate(void);
void setMonitoredTGs(const std::set<uint32_t>& tgs);
void setTg(uint32_t tg);
template <typename T>
void setRxParam(char id, const std::string& name, const T& value)
{
auto it = m_json_rx_map.find(id);
if (it != m_json_rx_map.end())
{
(it->second)[name] = value;
}
}
template <typename T>
void setTxParam(char id, const std::string& name, const T& value)
{
auto it = m_json_tx_map.find(id);
if (it != m_json_tx_map.end())
{
(it->second)[name] = value;
}
}
}; /* class ReflectorClient */
#endif /* REFLECTOR_CLIENT_INCLUDED */
/*
* This file has not been truncated
*/
File diff suppressed because it is too large. Load diff
+497
View File
@@ -0,0 +1,497 @@
/**
@file TGHandler.cpp
@brief A class for handling talk groups
@author Tobias Blomberg / SM0SVX
@date 2019-07-26
\verbatim
SvxReflector - An audio reflector for connecting SvxLink Servers
Copyright (C) 2003-2021 Tobias Blomberg / SM0SVX
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\endverbatim
*/
/****************************************************************************
*
* System Includes
*
****************************************************************************/
#include <iostream>
#include <cassert>
#include <algorithm>
#include <sstream>
#include <regex>
/****************************************************************************
*
* Project Includes
*
****************************************************************************/
/****************************************************************************
*
* Local Includes
*
****************************************************************************/
#include "TGHandler.h"
/****************************************************************************
*
* Namespaces to use
*
****************************************************************************/
using namespace std;
/****************************************************************************
*
* Defines & typedefs
*
****************************************************************************/
/****************************************************************************
*
* Local class definitions
*
****************************************************************************/
/****************************************************************************
*
* Prototypes
*
****************************************************************************/
/****************************************************************************
*
* Exported Global Variables
*
****************************************************************************/
/****************************************************************************
*
* Local Global Variables
*
****************************************************************************/
/****************************************************************************
*
* Public member functions
*
****************************************************************************/
TGHandler::TGHandler(void)
: m_cfg(0), m_timeout_timer(1000, Async::Timer::TYPE_PERIODIC),
m_sql_timeout(0), m_sql_timeout_blocktime(60)
{
m_timeout_timer.expired.connect(
mem_fun(*this, &TGHandler::checkTimers));
} /* TGHandler::TGHandler */
TGHandler::~TGHandler(void)
{
for (IdMap::iterator it = m_id_map.begin(); it != m_id_map.end(); ++it)
{
TGInfo* tg_info = it->second;
delete tg_info;
}
} /* TGHandler::~TGHandler */
void TGHandler::setSqlTimeoutBlocktime(unsigned sql_timeout_blocktime)
{
m_sql_timeout_blocktime = std::max(sql_timeout_blocktime, 1U);
} /* TGHandler::setSqlTimeoutBlocktime */
bool TGHandler::switchTo(ReflectorClient *client, uint32_t tg)
{
TGInfo *tg_info = 0;
ClientMap::iterator client_map_it = m_client_map.find(client);
if (client_map_it != m_client_map.end())
{
tg_info = client_map_it->second;
assert(tg_info != 0);
if (tg_info->id == tg)
{
return true;
}
removeClientP(tg_info, client);
}
if (tg > 0)
{
if (!allowTgSelection(client, tg))
{
return false;
}
IdMap::iterator id_map_it = m_id_map.find(tg);
if (id_map_it != m_id_map.end())
{
tg_info = id_map_it->second;
}
else
{
if (m_id_map.size() >= MAX_ACTIVE_TGS)
{
std::cerr << "*** WARNING: Maximum active TG limit ("
<< MAX_ACTIVE_TGS << ") reached, rejecting TG #"
<< tg << std::endl;
return false;
}
tg_info = new TGInfo(tg);
std::ostringstream ss;
ss << "TG#" << tg;
m_cfg->getValue(ss.str(), "AUTO_QSY_AFTER", tg_info->auto_qsy_after_s);
m_id_map[tg] = tg_info;
}
tg_info->clients.insert(client);
m_client_map[client] = tg_info;
}
//printTGStatus();
return true;
} /* TGHandler::switchTo */
void TGHandler::removeClient(ReflectorClient* client)
{
ClientMap::iterator client_map_it = m_client_map.find(client);
if (client_map_it != m_client_map.end())
{
TGInfo* tg_info = client_map_it->second;
if (tg_info->talker == client)
{
setTalkerForTG(tg_info->id, 0);
}
removeClientP(tg_info, client);
//printTGStatus();
}
} /* TGHandler::removeClient */
const TGHandler::ClientSet& TGHandler::clientsForTG(uint32_t tg) const
{
static const TGHandler::ClientSet empty_set;
IdMap::const_iterator id_map_it = m_id_map.find(tg);
if (id_map_it == m_id_map.end())
{
return empty_set;
}
return id_map_it->second->clients;
} /* TGHandler::clientsForTG */
void TGHandler::setTalkerForTG(uint32_t tg, ReflectorClient* new_talker)
{
IdMap::const_iterator id_map_it = m_id_map.find(tg);
if (id_map_it == m_id_map.end())
{
return;
}
TGInfo* tg_info = id_map_it->second;
ReflectorClient* old_talker = tg_info->talker;
if (new_talker == old_talker)
{
gettimeofday(&tg_info->last_talker_timestamp, NULL);
return;
}
tg_info->sql_timeout_cnt = (new_talker != 0) ? m_sql_timeout : 0;
id_map_it->second->talker = new_talker;
talkerUpdated(tg, old_talker, new_talker);
if (tg_info->auto_qsy_after_s > 0)
{
time_t now = time(NULL);
if ((new_talker == 0) && (now > tg_info->auto_qsy_time))
{
requestAutoQsy(tg_info->id);
tg_info->auto_qsy_time = now + tg_info->auto_qsy_after_s;
}
else if (tg_info->auto_qsy_time <= 0)
{
tg_info->auto_qsy_time = now + tg_info->auto_qsy_after_s;
}
}
//printTGStatus();
} /* TGHandler::setTalkerForTG */
ReflectorClient* TGHandler::talkerForTG(uint32_t tg) const
{
IdMap::const_iterator id_map_it = m_id_map.find(tg);
if (id_map_it == m_id_map.end())
{
return 0;
}
return id_map_it->second->talker;
} /* TGHandler::talkerForTG */
uint32_t TGHandler::TGForClient(ReflectorClient* client)
{
ClientMap::iterator client_map_it = m_client_map.find(client);
if (client_map_it == m_client_map.end())
{
return 0;
}
return client_map_it->second->id;
} /* TGHandler::TGForClient */
void TGHandler::setTrunkTalkerForTG(uint32_t tg, const std::string& callsign)
{
std::string old = trunkTalkerForTG(tg);
if (callsign == old)
{
return;
}
if (callsign.empty())
{
m_trunk_talkers.erase(tg);
}
else
{
if (m_trunk_talkers.find(tg) == m_trunk_talkers.end() &&
m_trunk_talkers.size() >= MAX_TRUNK_TALKERS)
{
std::cerr << "*** WARNING: Maximum trunk talker limit ("
<< MAX_TRUNK_TALKERS << ") reached, ignoring TG #"
<< tg << std::endl;
return;
}
m_trunk_talkers[tg] = callsign;
}
trunkTalkerUpdated(tg, old, callsign);
} /* TGHandler::setTrunkTalkerForTG */
void TGHandler::clearTrunkTalkerForTG(uint32_t tg)
{
setTrunkTalkerForTG(tg, "");
} /* TGHandler::clearTrunkTalkerForTG */
void TGHandler::clearAllTrunkTalkers(void)
{
std::vector<uint32_t> keys;
for (auto& kv : m_trunk_talkers)
{
keys.push_back(kv.first);
}
for (uint32_t tg : keys)
{
clearTrunkTalkerForTG(tg);
}
} /* TGHandler::clearAllTrunkTalkers */
std::string TGHandler::trunkTalkerForTG(uint32_t tg) const
{
auto it = m_trunk_talkers.find(tg);
return (it != m_trunk_talkers.end()) ? it->second : "";
} /* TGHandler::trunkTalkerForTG */
bool TGHandler::hasTrunkTalker(uint32_t tg) const
{
return m_trunk_talkers.count(tg) > 0;
} /* TGHandler::hasTrunkTalker */
bool TGHandler::allowTgSelection(ReflectorClient *client, uint32_t tg)
{
std::ostringstream ss;
ss << "TG#" << tg;
try
{
std::string allow;
if (m_cfg->getValue(ss.str(), "ALLOW", allow))
{
if (!std::regex_match(client->callsign(), std::regex(allow)))
{
return false;
}
//std::cout << "### " << client->callsign() << " Match!" << std::endl;
}
return true;
}
catch (std::regex_error& e)
{
std::cerr << "*** WARNING: Regular expression parsing error in "
<< ss.str() << "/ALLOW: " << e.what() << std::endl;
}
return false;
} /* TGHandler::allowTgSelection */
bool TGHandler::allowTgMonitoring(ReflectorClient *client, uint32_t tg)
{
if (!allowTgSelection(client, tg))
{
return false;
}
std::ostringstream ss;
ss << "TG#" << tg;
try
{
std::string allow;
if (m_cfg->getValue(ss.str(), "ALLOW_MONITOR", allow))
{
if (!std::regex_match(client->callsign(), std::regex(allow)))
{
return false;
}
}
return true;
}
catch (std::regex_error& e)
{
std::cerr << "*** WARNING: Regular expression parsing error in "
<< ss.str() << "/ALLOW_MONITOR: " << e.what() << std::endl;
}
return false;
} /* TGHandler::allowTgMonitoring */
bool TGHandler::showActivity(uint32_t tg) const
{
std::ostringstream ss;
ss << "TG#" << tg;
bool show_activity = true;
m_cfg->getValue(ss.str(), "SHOW_ACTIVITY", show_activity);
return show_activity;
} /* TGHandler::showActivity */
bool TGHandler::isRestricted(uint32_t tg) const
{
std::ostringstream ss;
ss << "TG#" << tg;
std::string allow;
return m_cfg->getValue(ss.str(), "ALLOW", allow);
} /* TGHandler::isRestricted */
/****************************************************************************
*
* Protected member functions
*
****************************************************************************/
/****************************************************************************
*
* Private member functions
*
****************************************************************************/
void TGHandler::checkTimers(Async::Timer *t)
{
struct timeval now;
gettimeofday(&now, NULL);
for (IdMap::iterator it = m_id_map.begin(); it != m_id_map.end(); ++it)
{
TGInfo *tg_info = it->second;
assert(tg_info != 0);
if (tg_info->talker != 0)
{
struct timeval diff;
timersub(&now, &tg_info->last_talker_timestamp, &diff);
if (diff.tv_sec > TALKER_AUDIO_TIMEOUT)
{
cout << tg_info->talker->callsign() << ": Talker audio timeout on TG #"
<< tg_info->id << endl;
setTalkerForTG(tg_info->id, 0);
}
if ((tg_info->sql_timeout_cnt > 0) && (--tg_info->sql_timeout_cnt == 0))
{
cout << tg_info->talker->callsign() << ": Talker audio timeout on TG #"
<< tg_info->id << endl;
tg_info->talker->setBlock(m_sql_timeout_blocktime);
setTalkerForTG(tg_info->id, 0);
}
}
}
} /* TGHandler::checkTimers */
void TGHandler::removeClientP(TGInfo *tg_info, ReflectorClient* client)
{
assert(tg_info != 0);
assert(client != 0);
if (client == tg_info->talker)
{
tg_info->talker = 0;
}
tg_info->clients.erase(client);
m_client_map.erase(client);
if (tg_info->clients.empty())
{
m_id_map.erase(tg_info->id);
delete tg_info;
}
} /* TGHandler::removeClientP */
void TGHandler::printTGStatus(void)
{
std::cout << "### ----------- BEGIN ----------------" << std::endl;
for (IdMap::const_iterator it = m_id_map.begin();
it != m_id_map.end(); ++it)
{
TGInfo *tg_info = it->second;
std::cout << "### " << tg_info->id << ": ";
for (ClientSet::const_iterator it = tg_info->clients.begin();
it != tg_info->clients.end(); ++it)
{
ReflectorClient* client = *it;
if (client == tg_info->talker)
{
std::cout << "*";
}
std::cout << client->callsign() << " ";
}
std::cout << std::endl;
}
std::cout << "### ------------ END -----------------" << std::endl;
} /* TGHandler::printTGStatus */
/*
* This file has not been truncated
*/
+242
View File
@@ -0,0 +1,242 @@
/**
@file TGHandler.h
@brief A class for handling talk groups
@author Tobias Blomberg / SM0SVX
@date 2019-07-25
\verbatim
SvxReflector - An audio reflector for connecting SvxLink Servers
Copyright (C) 2003-2024 Tobias Blomberg / SM0SVX
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\endverbatim
*/
#ifndef TG_HANDLER_INCLUDED
#define TG_HANDLER_INCLUDED
/****************************************************************************
*
* System Includes
*
****************************************************************************/
#include <map>
#include <set>
#include <string>
#include <sigc++/sigc++.h>
#include <sys/time.h>
/****************************************************************************
*
* Project Includes
*
****************************************************************************/
#include <AsyncConfig.h>
/****************************************************************************
*
* Local Includes
*
****************************************************************************/
#include "ReflectorClient.h"
/****************************************************************************
*
* Forward declarations
*
****************************************************************************/
/****************************************************************************
*
* Namespace
*
****************************************************************************/
//namespace MyNameSpace
//{
/****************************************************************************
*
* Forward declarations of classes inside of the declared namespace
*
****************************************************************************/
/****************************************************************************
*
* Defines & typedefs
*
****************************************************************************/
/****************************************************************************
*
* Exported Global Variables
*
****************************************************************************/
/****************************************************************************
*
* Class definitions
*
****************************************************************************/
/**
@brief Handle talk groups
@author Tobias Blomberg / SM0SVX
@date 2019-07-25
This class is responsible for keeping track of all talk groups that are used in
the system.
*/
class TGHandler : public sigc::trackable
{
public:
typedef std::set<ReflectorClient*> ClientSet;
static TGHandler* instance(void)
{
static TGHandler *tg_handler = new TGHandler;
return tg_handler;
}
/**
* @brief Default constructor
*/
TGHandler(void);
/**
* @brief Destructor
*/
~TGHandler(void);
/**
* @brief A_brief_member_function_description
* @param param1 Description_of_param1
* @return Return_value_of_this_member_function
*/
void setConfig(const Async::Config* cfg) { m_cfg = cfg; }
unsigned sqlTimeout(void) const { return m_sql_timeout; }
void setSqlTimeout(unsigned sql_timeout) { m_sql_timeout = sql_timeout; }
unsigned sqlTimeoutBlocktime(void) const
{
return m_sql_timeout_blocktime;
}
void setSqlTimeoutBlocktime(unsigned sql_timeout_blocktime);
bool switchTo(ReflectorClient *client, uint32_t tg);
void removeClient(ReflectorClient* client);
const ClientSet& clientsForTG(uint32_t tg) const;
void setTalkerForTG(uint32_t tg, ReflectorClient* client);
ReflectorClient* talkerForTG(uint32_t tg) const;
uint32_t TGForClient(ReflectorClient* client);
void setTrunkTalkerForTG(uint32_t tg, const std::string& callsign);
void clearTrunkTalkerForTG(uint32_t tg);
void clearAllTrunkTalkers(void);
std::string trunkTalkerForTG(uint32_t tg) const;
bool hasTrunkTalker(uint32_t tg) const;
const std::map<uint32_t, std::string>& trunkTalkersSnapshot(void) const
{
return m_trunk_talkers;
}
bool allowTgSelection(ReflectorClient *client, uint32_t tg);
bool allowTgMonitoring(ReflectorClient *client, uint32_t tg);
bool showActivity(uint32_t tg) const;
bool isRestricted(uint32_t tg) const;
sigc::signal<void(uint32_t,
ReflectorClient*, ReflectorClient*)> talkerUpdated;
sigc::signal<void(uint32_t)> requestAutoQsy;
// Fired when a trunk peer claims or releases a TG.
// Args: tg, old_callsign ("" = none), new_callsign ("" = none)
sigc::signal<void(uint32_t,
std::string, std::string)> trunkTalkerUpdated;
private:
static const time_t TALKER_AUDIO_TIMEOUT = 3; // Max three seconds gap
static const size_t MAX_ACTIVE_TGS = 10000;
static const size_t MAX_TRUNK_TALKERS = 10000;
struct TGInfo
{
uint32_t id;
ClientSet clients;
ReflectorClient* talker;
struct timeval last_talker_timestamp;
unsigned sql_timeout_cnt;
time_t auto_qsy_after_s;
time_t auto_qsy_time;
TGInfo(uint32_t tg)
: id(tg), talker(0), sql_timeout_cnt(0), auto_qsy_after_s(0),
auto_qsy_time(-1)
{
timerclear(&last_talker_timestamp);
}
};
typedef std::map<uint32_t, TGInfo*> IdMap;
typedef std::map<const ReflectorClient*, TGInfo*> ClientMap;
const Async::Config* m_cfg;
IdMap m_id_map;
ClientMap m_client_map;
std::map<uint32_t, std::string> m_trunk_talkers;
Async::Timer m_timeout_timer;
unsigned m_sql_timeout;
unsigned m_sql_timeout_blocktime;
TGHandler(const TGHandler&);
TGHandler& operator=(const TGHandler&);
void checkTimers(Async::Timer *t);
void removeClientP(TGInfo *tg_info, ReflectorClient* client);
void printTGStatus(void);
}; /* class TGHandler */
//} /* namespace */
#endif /* TG_HANDLER_INCLUDED */
/*
* This file has not been truncated
*/
+587
View File
@@ -0,0 +1,587 @@
/**
@file TrunkLink.cpp
@brief Server-to-server trunk link between two SvxReflector instances
@date 2026-03-20
\verbatim
SvxReflector - An audio reflector for connecting SvxLink Servers
Copyright (C) 2003-2026 Tobias Blomberg / SM0SVX
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\endverbatim
*/
/****************************************************************************
*
* System Includes
*
****************************************************************************/
#include <iostream>
#include <sstream>
#include <cassert>
#include <random>
#include <cerrno>
#include <cstring>
/****************************************************************************
*
* Project Includes
*
****************************************************************************/
#include <AsyncConfig.h>
#include <AsyncTcpConnection.h>
/****************************************************************************
*
* Local Includes
*
****************************************************************************/
#include "TrunkLink.h"
#include "ReflectorMsg.h"
#include "Reflector.h"
#include "TGHandler.h"
#include "ReflectorClient.h"
#include <json/json.h>
/****************************************************************************
*
* Namespaces to use
*
****************************************************************************/
using namespace std;
using namespace Async;
using namespace sigc;
static std::vector<std::string> splitPrefixes(const std::string& s)
{
std::vector<std::string> result;
std::istringstream ss(s);
std::string token;
while (std::getline(ss, token, ','))
{
token.erase(0, token.find_first_not_of(" \t"));
token.erase(token.find_last_not_of(" \t") + 1);
if (!token.empty())
result.push_back(token);
}
return result;
}
static std::string joinPrefixes(const std::vector<std::string>& v)
{
std::string result;
for (const auto& p : v)
{
if (!result.empty()) result += ',';
result += p;
}
return result;
}
/****************************************************************************
*
* TrunkLink public methods
*
****************************************************************************/
TrunkLink::TrunkLink(Reflector* reflector, Async::Config& cfg,
const std::string& section)
: m_reflector(reflector), m_cfg(cfg), m_section(section),
m_peer_port(5302), m_priority(0), m_peer_priority(0),
m_hello_received(false),
m_heartbeat_timer(1000, Timer::TYPE_PERIODIC, false),
m_hb_tx_cnt(0), m_hb_rx_cnt(0)
{
// Generate a random priority nonce for tie-breaking
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_int_distribution<uint32_t> dist;
m_priority = dist(rng);
m_con.connected.connect(mem_fun(*this, &TrunkLink::onConnected));
m_con.disconnected.connect(mem_fun(*this, &TrunkLink::onDisconnected));
m_con.frameReceived.connect(mem_fun(*this, &TrunkLink::onFrameReceived));
m_con.setMaxFrameSize(ReflectorMsg::MAX_POSTAUTH_FRAME_SIZE);
m_heartbeat_timer.expired.connect(
mem_fun(*this, &TrunkLink::heartbeatTick));
} /* TrunkLink::TrunkLink */
TrunkLink::~TrunkLink(void)
{
// Clear only trunk talkers held by this specific peer
for (uint32_t tg : m_peer_active_tgs)
{
TGHandler::instance()->clearTrunkTalkerForTG(tg);
}
m_peer_active_tgs.clear();
} /* TrunkLink::~TrunkLink */
bool TrunkLink::initialize(void)
{
// HOST
if (!m_cfg.getValue(m_section, "HOST", m_peer_host) || m_peer_host.empty())
{
cerr << "*** ERROR[" << m_section << "]: Missing HOST" << endl;
return false;
}
// PORT (optional, default 5302)
m_cfg.getValue(m_section, "PORT", m_peer_port);
// SECRET
if (!m_cfg.getValue(m_section, "SECRET", m_secret) || m_secret.empty())
{
cerr << "*** ERROR[" << m_section << "]: Missing SECRET" << endl;
return false;
}
// LOCAL_PREFIX — comma-separated list of this reflector's owned TG prefixes
std::string local_prefix_str;
m_cfg.getValue("GLOBAL", "LOCAL_PREFIX", local_prefix_str);
m_local_prefix = splitPrefixes(local_prefix_str);
if (m_local_prefix.empty())
{
cerr << "*** ERROR: Missing or empty LOCAL_PREFIX in [GLOBAL]" << endl;
return false;
}
// REMOTE_PREFIX — comma-separated list of the peer's owned TG prefixes
std::string remote_prefix_str;
if (!m_cfg.getValue(m_section, "REMOTE_PREFIX", remote_prefix_str) ||
remote_prefix_str.empty())
{
cerr << "*** ERROR[" << m_section << "]: Missing REMOTE_PREFIX" << endl;
return false;
}
m_remote_prefix = splitPrefixes(remote_prefix_str);
if (m_remote_prefix.empty())
{
cerr << "*** ERROR[" << m_section << "]: Invalid REMOTE_PREFIX" << endl;
return false;
}
cout << m_section << ": Trunk to " << m_peer_host << ":" << m_peer_port
<< " local_prefix=" << joinPrefixes(m_local_prefix)
<< " remote_prefix=" << joinPrefixes(m_remote_prefix) << endl;
m_con.addStaticSRVRecord(0, 0, 0, m_peer_port, m_peer_host);
m_con.connect();
return true;
} /* TrunkLink::initialize */
bool TrunkLink::isSharedTG(uint32_t tg) const
{
const std::string s = std::to_string(tg);
for (const auto& prefix : m_remote_prefix)
{
if (s.size() >= prefix.size() &&
s.compare(0, prefix.size(), prefix) == 0)
return true;
}
return false;
} /* TrunkLink::isSharedTG */
Json::Value TrunkLink::statusJson(void) const
{
Json::Value obj(Json::objectValue);
obj["host"] = m_peer_host;
obj["port"] = m_peer_port;
obj["connected"] = m_con.isConnected();
Json::Value local_arr(Json::arrayValue);
for (const auto& p : m_local_prefix) local_arr.append(p);
obj["local_prefix"] = local_arr;
Json::Value remote_arr(Json::arrayValue);
for (const auto& p : m_remote_prefix) remote_arr.append(p);
obj["remote_prefix"] = remote_arr;
// active_talkers: all TGs currently held by trunk that match our remote prefix
Json::Value talkers(Json::objectValue);
const auto& trunk_map = TGHandler::instance()->trunkTalkersSnapshot();
for (auto& kv : trunk_map)
{
if (isSharedTG(kv.first))
{
talkers[std::to_string(kv.first)] = kv.second;
}
}
obj["active_talkers"] = talkers;
return obj;
} /* TrunkLink::statusJson */
void TrunkLink::onLocalTalkerStart(uint32_t tg, const std::string& callsign)
{
if (!m_con.isConnected() || !m_hello_received || !isSharedTG(tg))
{
return;
}
sendMsg(MsgTrunkTalkerStart(tg, callsign));
} /* TrunkLink::onLocalTalkerStart */
void TrunkLink::onLocalTalkerStop(uint32_t tg)
{
if (!m_con.isConnected() || !m_hello_received || !isSharedTG(tg))
{
return;
}
// If we cleared our local talker because we were yielding to this peer,
// don't send TrunkTalkerStop — the peer already owns the TG.
if (m_yielded_tgs.count(tg))
{
return;
}
sendMsg(MsgTrunkTalkerStop(tg));
} /* TrunkLink::onLocalTalkerStop */
void TrunkLink::onLocalAudio(uint32_t tg, const std::vector<uint8_t>& audio)
{
if (!m_con.isConnected() || !m_hello_received || !isSharedTG(tg) ||
m_yielded_tgs.count(tg))
{
return;
}
sendMsg(MsgTrunkAudio(tg, audio));
} /* TrunkLink::onLocalAudio */
void TrunkLink::onLocalFlush(uint32_t tg)
{
if (!m_con.isConnected() || !m_hello_received || !isSharedTG(tg))
{
return;
}
sendMsg(MsgTrunkFlush(tg));
} /* TrunkLink::onLocalFlush */
/****************************************************************************
*
* TrunkLink private methods
*
****************************************************************************/
void TrunkLink::onConnected(void)
{
cout << m_section << ": Connected to " << m_con.remoteHost()
<< ":" << m_con.remotePort() << endl;
m_hello_received = false;
m_yielded_tgs.clear();
m_peer_active_tgs.clear();
m_hb_tx_cnt = HEARTBEAT_TX_CNT_RESET;
m_hb_rx_cnt = HEARTBEAT_RX_CNT_RESET;
// Regenerate priority nonce for each new connection
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_int_distribution<uint32_t> dist;
m_priority = dist(rng);
sendMsg(MsgTrunkHello(m_section, joinPrefixes(m_local_prefix), m_priority,
m_secret));
m_heartbeat_timer.setEnable(true);
} /* TrunkLink::onConnected */
void TrunkLink::onDisconnected(TcpConnection* con,
TcpConnection::DisconnectReason reason)
{
cout << m_section << ": Disconnected from " << m_con.remoteHost()
<< ":" << m_con.remotePort() << ": "
<< TcpConnection::disconnectReasonStr(reason) << endl;
m_heartbeat_timer.setEnable(false);
m_hello_received = false;
// Release only trunk talkers held by this peer
for (uint32_t tg : m_peer_active_tgs)
{
TGHandler::instance()->clearTrunkTalkerForTG(tg);
}
m_peer_active_tgs.clear();
m_yielded_tgs.clear();
} /* TrunkLink::onDisconnected */
void TrunkLink::onFrameReceived(FramedTcpConnection* con,
std::vector<uint8_t>& data)
{
auto buf = reinterpret_cast<const char*>(data.data());
stringstream ss;
ss.write(buf, data.size());
ReflectorMsg header;
if (!header.unpack(ss))
{
cerr << "*** ERROR[" << m_section << "]: Failed to unpack trunk message "
"header" << endl;
return;
}
// Only allow hello and heartbeat before authentication completes
if (!m_hello_received &&
header.type() != MsgTrunkHello::TYPE &&
header.type() != MsgTrunkHeartbeat::TYPE)
{
cerr << "*** WARNING[" << m_section
<< "]: Ignoring trunk message type=" << header.type()
<< " before hello" << endl;
return;
}
m_hb_rx_cnt = HEARTBEAT_RX_CNT_RESET;
switch (header.type())
{
case MsgTrunkHeartbeat::TYPE:
handleMsgTrunkHeartbeat();
break;
case MsgTrunkHello::TYPE:
handleMsgTrunkHello(ss);
break;
case MsgTrunkTalkerStart::TYPE:
handleMsgTrunkTalkerStart(ss);
break;
case MsgTrunkTalkerStop::TYPE:
handleMsgTrunkTalkerStop(ss);
break;
case MsgTrunkAudio::TYPE:
handleMsgTrunkAudio(ss);
break;
case MsgTrunkFlush::TYPE:
handleMsgTrunkFlush(ss);
break;
default:
cerr << "*** WARNING[" << m_section
<< "]: Unknown trunk message type=" << header.type() << endl;
break;
}
} /* TrunkLink::onFrameReceived */
void TrunkLink::handleMsgTrunkHeartbeat(void)
{
// rx counter already reset in onFrameReceived
} /* TrunkLink::handleMsgTrunkHeartbeat */
void TrunkLink::handleMsgTrunkHello(std::istream& is)
{
MsgTrunkHello msg;
if (!msg.unpack(is))
{
cerr << "*** ERROR[" << m_section << "]: Failed to unpack MsgTrunkHello"
<< endl;
return;
}
if (msg.id().empty())
{
cerr << "*** ERROR[" << m_section
<< "]: Peer sent empty trunk ID in MsgTrunkHello" << endl;
m_con.disconnect();
return;
}
// Verify shared secret via HMAC
if (!msg.verify(m_secret))
{
cerr << "*** ERROR[" << m_section
<< "]: Trunk authentication failed — peer '" << msg.id()
<< "' sent invalid secret (HMAC mismatch)" << endl;
m_con.disconnect();
return;
}
m_peer_priority = msg.priority();
m_hello_received = true;
cout << m_section << ": Trunk hello from peer '" << msg.id()
<< "' local_prefix=" << msg.localPrefix()
<< " priority=" << m_peer_priority
<< " (authenticated)" << endl;
} /* TrunkLink::handleMsgTrunkHello */
void TrunkLink::handleMsgTrunkTalkerStart(std::istream& is)
{
MsgTrunkTalkerStart msg;
if (!msg.unpack(is))
{
cerr << "*** ERROR[" << m_section
<< "]: Failed to unpack MsgTrunkTalkerStart" << endl;
return;
}
uint32_t tg = msg.tg();
if (!isSharedTG(tg))
{
return;
}
// Tie-break: if we already have a local talker on this TG, decide who wins.
// Lower priority value wins. If equal (shouldn't happen), local wins.
ReflectorClient* local_talker = TGHandler::instance()->talkerForTG(tg);
if (local_talker != nullptr)
{
if (m_priority <= m_peer_priority)
{
// We win — ignore peer's claim
cout << m_section << ": TG #" << tg
<< " conflict — local wins (our priority=" << m_priority
<< " <= peer=" << m_peer_priority << ")" << endl;
return;
}
// We defer — clear local talker and accept remote
cout << m_section << ": TG #" << tg
<< " conflict — deferring to peer (our priority=" << m_priority
<< " > peer=" << m_peer_priority << ")" << endl;
m_yielded_tgs.insert(tg);
TGHandler::instance()->setTalkerForTG(tg, nullptr);
// onTalkerUpdated will fire; Reflector must not re-send TrunkTalkerStart
// for this TG since it's in m_yielded_tgs (checked in Reflector.cpp)
}
m_peer_active_tgs.insert(tg);
TGHandler::instance()->setTrunkTalkerForTG(tg, msg.callsign());
} /* TrunkLink::handleMsgTrunkTalkerStart */
void TrunkLink::handleMsgTrunkTalkerStop(std::istream& is)
{
MsgTrunkTalkerStop msg;
if (!msg.unpack(is))
{
cerr << "*** ERROR[" << m_section
<< "]: Failed to unpack MsgTrunkTalkerStop" << endl;
return;
}
uint32_t tg = msg.tg();
if (!isSharedTG(tg))
{
return;
}
m_yielded_tgs.erase(tg);
m_peer_active_tgs.erase(tg);
TGHandler::instance()->clearTrunkTalkerForTG(tg);
} /* TrunkLink::handleMsgTrunkTalkerStop */
void TrunkLink::handleMsgTrunkAudio(std::istream& is)
{
MsgTrunkAudio msg;
if (!msg.unpack(is))
{
cerr << "*** ERROR[" << m_section
<< "]: Failed to unpack MsgTrunkAudio" << endl;
return;
}
uint32_t tg = msg.tg();
if (!isSharedTG(tg) || msg.audio().empty())
{
return;
}
// Only forward audio if this peer has claimed the TG via TalkerStart
if (m_peer_active_tgs.find(tg) == m_peer_active_tgs.end())
{
return;
}
// Rebuild a UDP audio message and broadcast to local clients on this TG
MsgUdpAudio udp_msg(msg.audio());
m_reflector->broadcastUdpMsg(udp_msg, ReflectorClient::TgFilter(tg));
} /* TrunkLink::handleMsgTrunkAudio */
void TrunkLink::handleMsgTrunkFlush(std::istream& is)
{
MsgTrunkFlush msg;
if (!msg.unpack(is))
{
cerr << "*** ERROR[" << m_section
<< "]: Failed to unpack MsgTrunkFlush" << endl;
return;
}
uint32_t tg = msg.tg();
if (!isSharedTG(tg))
{
return;
}
m_reflector->broadcastUdpMsg(MsgUdpFlushSamples(),
ReflectorClient::TgFilter(tg));
} /* TrunkLink::handleMsgTrunkFlush */
void TrunkLink::sendMsg(const ReflectorMsg& msg)
{
ostringstream ss;
ReflectorMsg header(msg.type());
if (!header.pack(ss) || !msg.pack(ss))
{
cerr << "*** ERROR[" << m_section << "]: Failed to pack trunk message "
"type=" << msg.type() << endl;
return;
}
m_hb_tx_cnt = HEARTBEAT_TX_CNT_RESET;
m_con.write(ss.str().data(), ss.str().size());
} /* TrunkLink::sendMsg */
void TrunkLink::heartbeatTick(Async::Timer* t)
{
if (--m_hb_tx_cnt == 0)
{
sendMsg(MsgTrunkHeartbeat());
}
if (--m_hb_rx_cnt == 0)
{
cerr << "*** ERROR[" << m_section
<< "]: Trunk heartbeat timeout — disconnecting" << endl;
m_con.disconnect();
}
} /* TrunkLink::heartbeatTick */
/*
* This file has not been truncated
*/
+163
View File
@@ -0,0 +1,163 @@
/**
@file TrunkLink.h
@brief Server-to-server trunk link between two SvxReflector instances
@date 2026-03-20
\verbatim
SvxReflector - An audio reflector for connecting SvxLink Servers
Copyright (C) 2003-2026 Tobias Blomberg / SM0SVX
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\endverbatim
*/
#ifndef TRUNK_LINK_INCLUDED
#define TRUNK_LINK_INCLUDED
/****************************************************************************
*
* System Includes
*
****************************************************************************/
#include <set>
#include <string>
#include <vector>
#include <sigc++/sigc++.h>
#include <json/json.h>
/****************************************************************************
*
* Project Includes
*
****************************************************************************/
#include <AsyncConfig.h>
#include <AsyncTcpPrioClient.h>
#include <AsyncFramedTcpConnection.h>
#include <AsyncTimer.h>
/****************************************************************************
*
* Forward declarations
*
****************************************************************************/
class Reflector;
class ReflectorMsg;
class MsgUdpAudio;
/****************************************************************************
*
* Class definitions
*
****************************************************************************/
/**
@brief Manages a persistent TCP trunk connection to a peer SvxReflector
One TrunkLink instance is created per [TRUNK_x] config section. It connects
outbound to the peer reflector on the configured port, exchanges a handshake
(MsgTrunkHello), then forwards talker state and audio in both directions for
the set of shared TGs.
Talker arbitration tie-break: each side generates a random 32-bit priority at
startup and exchanges it in MsgTrunkHello. When both sides claim the same TG
simultaneously, the side with the lower priority value defers (clears its local
talker and accepts the remote one).
*/
class TrunkLink : public sigc::trackable
{
public:
TrunkLink(Reflector* reflector, Async::Config& cfg,
const std::string& section);
~TrunkLink(void);
bool initialize(void);
bool isSharedTG(uint32_t tg) const;
const std::string& section(void) const { return m_section; }
Json::Value statusJson(void) const;
// Called by Reflector when a local client starts/stops on a shared TG
void onLocalTalkerStart(uint32_t tg, const std::string& callsign);
void onLocalTalkerStop(uint32_t tg);
// Called by Reflector for each audio frame from a local talker on a shared TG
void onLocalAudio(uint32_t tg, const std::vector<uint8_t>& audio);
// Called by Reflector when a local talker's audio stream ends
void onLocalFlush(uint32_t tg);
private:
static const unsigned HEARTBEAT_TX_CNT_RESET = 10;
static const unsigned HEARTBEAT_RX_CNT_RESET = 15;
using FramedTcpClient =
Async::TcpPrioClient<Async::FramedTcpConnection>;
Reflector* m_reflector;
Async::Config& m_cfg;
std::string m_section;
std::string m_peer_host;
uint16_t m_peer_port;
std::string m_secret;
std::vector<std::string> m_local_prefix; // our authoritative TG prefixes
std::vector<std::string> m_remote_prefix; // peer's authoritative TG prefixes
uint32_t m_priority; // our tie-break nonce (random)
uint32_t m_peer_priority; // peer's nonce, from MsgTrunkHello
bool m_hello_received;
FramedTcpClient m_con;
Async::Timer m_heartbeat_timer;
unsigned m_hb_tx_cnt;
unsigned m_hb_rx_cnt;
// TGs where we suppressed our local talker to defer to the peer
std::set<uint32_t> m_yielded_tgs;
// TGs currently held by this specific trunk peer (for scoped cleanup)
std::set<uint32_t> m_peer_active_tgs;
TrunkLink(const TrunkLink&);
TrunkLink& operator=(const TrunkLink&);
void onConnected(void);
void onDisconnected(Async::TcpConnection* con,
Async::TcpConnection::DisconnectReason reason);
void onFrameReceived(Async::FramedTcpConnection* con,
std::vector<uint8_t>& data);
void handleMsgTrunkHello(std::istream& is);
void handleMsgTrunkTalkerStart(std::istream& is);
void handleMsgTrunkTalkerStop(std::istream& is);
void handleMsgTrunkAudio(std::istream& is);
void handleMsgTrunkFlush(std::istream& is);
void handleMsgTrunkHeartbeat(void);
void sendMsg(const ReflectorMsg& msg);
void heartbeatTick(Async::Timer* t);
}; /* class TrunkLink */
#endif /* TRUNK_LINK_INCLUDED */
/*
* This file has not been truncated
*/
+366
View File
@@ -0,0 +1,366 @@
#!/usr/bin/env python3
"""\
CA hook script for the SvxReflector server application.
This script will be called by the SvxReflector application on some CA events.
The type of event will be available in the CA_OP environment variable. The
following event types are available for CA_OP.
- PENDING_CSR_CREATE: A new CSR (Certificate Signing Request) is received
- PENDING_CSR_UPDATED: An updated CSR is received
- CSR_SIGNED: A CSR is signed
- CRT_RENEWED: A certificate is renewed
The PEM conents is available in the following environment variables.
- CA_CSR_PEM -- The CSR PEM contents
- CA_CRT_PEM -- The certificate PEM contents, including intermediates
"""
import os
import os.path
import sys
import socket
import yaml
from cryptography import x509
from cryptography.x509.oid import NameOID, ExtensionOID
from cryptography.x509.extensions import ExtensionNotFound
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
from email.message import EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import smtplib
config = {}
def load_config() -> None:
"""\
Find the configuration file and load it into the config dict
"""
global config
FILENAME = "ca-hook.yaml"
path = f"@SVX_SYSCONF_INSTALL_DIR@/{FILENAME}"
if os.path.exists(FILENAME):
path = FILENAME
elif home := os.getenv("HOME"):
p = f"{home}/.svxlink/{FILENAME}"
if os.path.exists(p):
path = p
with open(path, "r") as f:
config = yaml.safe_load(f)
def config_format(varname, values):
"""\
Get the value of the specified configuration variable. If it is a string,
pass it through formatting. Otherwise return the config variable as is.
"""
if not varname in config:
return None
return (
config[varname].format(**values)
if isinstance(config[varname], str)
else config[varname]
)
def config_is_set(varnames: set) -> bool:
for varname in varnames:
if not varname in config or config[varname] is None:
return False
return True
def send_email(**kwargs) -> int:
"""\
Send and email using the following keyword arguments.
to: A list of destination addresses
bcc: A list of BCC addresses
subject: The subject of the message
content: The contents of the message
The global variable EMAIL_FROM will be used as the sender.
The global variable EMAIL_SMTP_SERVER will be used as the SMTP server to
send the message to.
"""
msg = MIMEMultipart()
msg["From"] = config["EMAIL_FROM"]
msg["To"] = (
", ".join(kwargs["to"])
if isinstance(kwargs["to"], list)
else kwargs["to"]
)
if kwargs.get("bcc"):
msg["BCC"] = (
", ".join(kwargs["bcc"])
if isinstance(kwargs["bcc"], list)
else kwargs["bcc"]
)
msg["Subject"] = kwargs["subject"]
msg.attach(MIMEText(kwargs["content"]))
if "attachments" in kwargs:
for attachment in kwargs["attachments"]:
part = MIMEText(attachment["content"])
part["Content-Disposition"] = (
f"attachment; filename=\"{attachment['name']}\""
)
msg.attach(part)
if config["EMAIL_DEBUG"]:
print(msg)
else:
s = smtplib.SMTP(config["EMAIL_SMTP_SERVER"])
s.send_message(msg)
s.quit()
return 0
def pending_csr_create(csr) -> int:
"""\
Called when a pending CSR is created.
"""
if not config_is_set(
{
"CSR_CREATE_MAIL_TO",
"CSR_CREATE_MAIL_SUBJECT",
"CSR_CREATE_MAIL_CONTENT",
}
):
return 0
cn = csr.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
callsign = cn[0].value if len(cn) > 0 else ""
email = []
san = None
try:
san = csr.extensions.get_extension_for_oid(
ExtensionOID.SUBJECT_ALTERNATIVE_NAME
)
email = san.value.get_values_for_type(x509.RFC822Name)
except ExtensionNotFound:
pass
# print(f"### Create CSR: callsign={callsign} email={email}")
values = {
"callsign": callsign,
"subject": csr.subject.rfc4514_string(),
"hostname": socket.gethostname(),
"email": ", ".join(email),
}
send_email(
to=config_format("CSR_CREATE_MAIL_TO", values),
bcc=config_format("CSR_CREATE_MAIL_BCC", values),
subject=config["CSR_CREATE_MAIL_SUBJECT"].format(**values),
content=config["CSR_CREATE_MAIL_CONTENT"].format(**values),
attachments=[
{
"name": f"{callsign}.csr",
"content": csr.public_bytes(
serialization.Encoding.PEM
).decode(),
}
],
)
return 0
def pending_csr_update(csr) -> int:
"""\
Called when a pending CSR is updated.
"""
if not config_is_set(
{
"CSR_UPDATE_MAIL_TO",
"CSR_UPDATE_MAIL_SUBJECT",
"CSR_UPDATE_MAIL_CONTENT",
}
):
return 0
cn = csr.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
callsign = cn[0].value if len(cn) > 0 else ""
email = []
san = None
try:
san = csr.extensions.get_extension_for_oid(
ExtensionOID.SUBJECT_ALTERNATIVE_NAME
)
email = san.value.get_values_for_type(x509.RFC822Name)
except ExtensionNotFound:
pass
# print(f"### Update CSR: callsign={callsign} email={email}")
values = {
"callsign": callsign,
"subject": csr.subject.rfc4514_string(),
"hostname": socket.gethostname(),
"email": ", ".join(email),
}
send_email(
to=config_format("CSR_UPDATE_MAIL_TO", values),
bcc=config_format("CSR_UPDATE_MAIL_BCC", values),
subject=config["CSR_UPDATE_MAIL_SUBJECT"].format(**values),
content=config["CSR_UPDATE_MAIL_CONTENT"].format(**values),
attachments=[
{
"name": f"{callsign}.csr",
"content": csr.public_bytes(
serialization.Encoding.PEM
).decode(),
}
],
)
return 0
def csr_signed(cert) -> int:
"""\
Called when a CSR is signed.
"""
if not config_is_set(
{
"CSR_SIGNED_MAIL_TO",
"CSR_SIGNED_MAIL_SUBJECT",
"CSR_SIGNED_MAIL_CONTENT",
}
):
return 0
cn = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
callsign = cn[0].value if len(cn) > 0 else ""
email = []
try:
san = cert.extensions.get_extension_for_oid(
ExtensionOID.SUBJECT_ALTERNATIVE_NAME
)
email = san.value.get_values_for_type(x509.RFC822Name)
except ExtensionNotFound:
pass
# print(f"### Sign CSR: callsign={callsign} email={email}")
values = {
"callsign": callsign,
"serial_number": cert.serial_number,
"issuer": cert.issuer.rfc4514_string(),
"subject": cert.subject.rfc4514_string(),
"not_before": cert.not_valid_before,
"not_after": cert.not_valid_after,
"email": ", ".join(email),
"hostname": socket.gethostname(),
}
send_email(
to=config_format("CSR_SIGNED_MAIL_TO", values),
bcc=config_format("CSR_SIGNED_MAIL_BCC", values),
subject=config["CSR_SIGNED_MAIL_SUBJECT"].format(**values),
content=config["CSR_SIGNED_MAIL_CONTENT"].format(**values),
)
return 0
def crt_renewed(cert) -> int:
"""\
Called when a certificate is renewed.
"""
if not config_is_set(
{
"CRT_RENEWED_MAIL_TO",
"CRT_RENEWED_MAIL_SUBJECT",
"CRT_RENEWED_MAIL_CONTENT",
}
):
return 0
cn = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
callsign = cn[0].value if len(cn) > 0 else ""
email = []
try:
san = cert.extensions.get_extension_for_oid(
ExtensionOID.SUBJECT_ALTERNATIVE_NAME
)
email = san.value.get_values_for_type(x509.RFC822Name)
except ExtensionNotFound:
pass
# print(f"### Renew cert: callsign={callsign} email={email}")
values = {
"callsign": callsign,
"serial_number": cert.serial_number,
"issuer": cert.issuer.rfc4514_string(),
"subject": cert.subject.rfc4514_string(),
"not_before": cert.not_valid_before,
"not_after": cert.not_valid_after,
"email": ", ".join(email),
"hostname": socket.gethostname(),
}
send_email(
to=config_format("CRT_RENEWED_MAIL_TO", values),
bcc=config_format("CRT_RENEWED_MAIL_BCC", values),
subject=config["CRT_RENEWED_MAIL_SUBJECT"].format(**values),
content=config["CRT_RENEWED_MAIL_CONTENT"].format(**values),
)
return 0
def main() -> int:
"""\
The main entry point for the this script.
"""
load_config()
op = os.getenv("CA_OP")
if not op:
print(f"*** ERROR: The CA_OP environment variable is not set or empty")
return 1
if op != "CSR_SIGNED" and op != "CRT_RENEWED":
csr_pem = os.getenv("CA_CSR_PEM")
if not csr_pem:
print("*** ERROR: CA_CSR_PEM not set")
return 1
if csr_pem:
csr = x509.load_pem_x509_csr(csr_pem.encode(), default_backend())
else:
print("*** ERROR: Invalid CSR PEM")
return 1
if op == "PENDING_CSR_CREATE":
return pending_csr_create(csr)
elif op == "PENDING_CSR_UPDATE":
return pending_csr_update(csr)
elif op == "CSR_SIGNED":
certs_pem = os.getenv("CA_CRT_PEM")
if not certs_pem:
print("*** ERROR: CA_CRT_PEM not set")
return 1
cert = x509.load_pem_x509_certificate(
certs_pem.encode(), default_backend()
)
return csr_signed(cert)
elif op == "CRT_RENEWED":
certs_pem = os.getenv("CA_CRT_PEM")
if not certs_pem:
print("*** ERROR: CA_CRT_PEM not set")
return 1
cert = x509.load_pem_x509_certificate(
certs_pem.encode(), default_backend()
)
return crt_renewed(cert)
return 0
if __name__ == "__main__":
sys.exit(main())
+153
View File
@@ -0,0 +1,153 @@
---
###############################################################################
#
# Configuration file for the ca-hook.py SvxReflector server CA events hook
# script.
#
# For the *_MAIL_TO and *_MAIL_BCC configuration variables it is possible to
# embed the following variables inside curly braces.
#
# email: The email addresses included in the CSR/CRT
#
# For the CSR_CREATE_MAIL_SUBJECT, CSR_CREATE_MAIL_CONTENT,
# CSR_UPDATE_MAIL_SUBJECT and CSR_UPDATE_MAIL_CONTENT configuration
# variables it is possible to embed the following variables inside curly
# braces.
#
# callsign: The callsign (Subject CN)
# subject: The Subject DN of the CSR
# email: The email addresses included in the CSR/CRT
# hostname: The name of the host where this script run
#
# In addition to the above variables, the following ones can be embedded in the
# CSR_SIGNED_MAIL_SUBJECT, CSR_SIGNED_MAIL_CONTENT, CRT_RENEWED_MAIL_SUBJECT
# and CRT_RENEWED_MAIL_CONTENT configuration variables.
#
# serial_number: The serial number of the certificate
# issuer: The certificate issuer Subject DN
# not_before When the certificate is valid from
# not_after When the certificate will expire
#
###############################################################################
# Set to true to print the mail message instead of sending it
EMAIL_DEBUG: true
# The SMTP server to send the message to
EMAIL_SMTP_SERVER: "127.0.0.1"
# Use the following email sender address ("From")
EMAIL_FROM: "SvxReflector <reflector@example.com>"
# Send sysop mails to the following addresses
SYSOP_EMAIL: &SYSOP_EMAIL
- "sysop1@example.com"
- "sysop2@example.com"
# Send the CSR create emails to the following addresses
CSR_CREATE_MAIL_TO: *SYSOP_EMAIL
# Send the CSR create emails to the following BCC addresses
CSR_CREATE_MAIL_BCC:
# Email subject to use for CSR create notifications.
# Comment out to suppress sending of CSR create emails.
CSR_CREATE_MAIL_SUBJECT: "SvxReflector: CSR received from node {callsign}"
# Email content to use for CSR create notifications.
# Comment out to suppress sending of CSR create emails.
CSR_CREATE_MAIL_CONTENT: |
Hi,
The reflector node {callsign} has submitted a CSR at reflector server {hostname}. Please check that the CSR is correct and then sign it.
Subject: {subject}
Email: {email}
Regards,
SvxReflector Server
# Send the CSR update emails to the following addresses
CSR_UPDATE_MAIL_TO: *SYSOP_EMAIL
# Send the CSR update emails to the following BCC addresses
CSR_UPDATE_MAIL_BCC:
# Email subject to use for CSR update notifications.
# Comment out to suppress sending of CSR update emails.
CSR_UPDATE_MAIL_SUBJECT: "SvxReflector: CSR update received from node {callsign}"
# Email content to use for CSR update notifications.
# Comment out to suppress sending of CSR update emails.
CSR_UPDATE_MAIL_CONTENT: |
Hi,
The reflector node {callsign} has submitted an updated CSR at reflector server {hostname}. Please check that the CSR is correct and then sign it.
Subject: {subject}
Email: {email}
Regards,
SvxReflector Server
# Send the CSR signed emails to the following addresses
CSR_SIGNED_MAIL_TO: "{email}"
# Send the CSR signed emails to the following BCC addresses
CSR_SIGNED_MAIL_BCC: *SYSOP_EMAIL
# Email subject to use for CSR signed notifications.
# Comment out to suppress sending of CSR signed emails.
CSR_SIGNED_MAIL_SUBJECT: "SvxReflector: Certificate signed for node {callsign}"
# Email content to use for CSR signed notifications.
# Comment out to suppress sending of CSR signed emails.
CSR_SIGNED_MAIL_CONTENT: |
Hi,
The certificate for reflector node {callsign} has been signed and is now ready for use. If this was not initiated by you, your callsign may have been hijacked by someone. In that case, please reply to this email to notify the reflector sysop.
Serial: {serial_number:X}
Issuer: {issuer}
Subject: {subject}
Not before: {not_before}Z
Not after: {not_after}Z
Email: {email}
If everything is in order, you do not have to do anything. Your node will receive the certificate from the reflector server and will start to use it immediately.
Regards,
SvxReflector Server Sysop
# Send the certificate renewed emails to the following addresses
CRT_RENEWED_MAIL_TO: *SYSOP_EMAIL
# Send the certificate renewed emails to the following BCC addresses
CRT_RENEWED_MAIL_BCC:
# Email subject to use for certificate renew notifications.
# Comment out to suppress sending of renew emails.
CRT_RENEWED_MAIL_SUBJECT: "SvxReflector: Certificate renewed for node {callsign}"
# Email content to use for certificate renew notifications.
# Comment out to suppress sending of CSR signed emails.
CRT_RENEWED_MAIL_CONTENT: |
Hi,
The certificate for reflector node {callsign} has been renewed and is now ready for use. Node certificates are automatically renewed when about one third of the total certificate lifetime remains.
Serial: {serial_number:X}
Issuer: {issuer}
Subject: {subject}
Not before: {not_before}Z
Not after: {not_after}Z
Email: {email}
If everything is in order, you do not have to do anything. Your node will receive the new certificate from the reflector server and will start to use it immediately.
Regards,
SvxReflector Server Sysop
+2
View File
@@ -0,0 +1,2 @@
README.html
db
+103
View File
@@ -0,0 +1,103 @@
= SvxReflector Password Generator
:toc2:
== Introduction
This is a simple web utility used to safely generate a password for a SvxLink
node to log in to the SvxReflector. The utility offer random generated
passwords to a client which can then be picked up by the reflector sysop to be
configured in the reflector configuration file. The generated password is
protected in transit by using a SSL/TLS encrypted connection.
== Installation
This utility should be installed on a webserver where the SvxReflector sysop
have shell access. It does not have to be the same server as where the
SvxReflector server is running.
The Apache webserver must be installed as a prerequisite. That setup is not
described in this documentation. The webserver also need to be set up with a
valid SSL/TLS server certificate.
It is of course possible to use other web servers but this is not described in
this document.
In short, the installation is done by installing a couple of dependencies and
then copy the genpw files in place.
[source,bash]
----
apt update
apt install libapache2-mod-wsgi-py3 python3-flask
mkdir -p /var/www/genpw/db
cp genpw.* /var/www/genpw/
cp getpw.py /usr/local/bin/
useradd -rU svxlink
chown svxlink:svxlink /var/www/genpw/db
chmod 2770 /var/www/genpw/db
usermod -aG sysop1 svxlink
usermod -aG sysop2 svxlink
----
== Apache Config Example
When all genpw files have been put in place by following the instructions above
Apache must be configured with something like the example below.
[source,apache]
----
<IfModule mod_ssl.c>
<VirtualHost *:443>
# ...
# Other setup
# ...
# Make sure that SSL/TLS encryption is enabled/required
SSLEngine on
SSLCertificateFile /etc/ssl/certs/example.org.crt
SSLCertificateKeyFile /etc/ssl/private/example.org.key
SSLCertificateChainFile /etc/ssl/certs/example.org-intermediate.pem
SSLProtocol -all +TLSv1.2 +TLSv1.3
WSGIDaemonProcess genpw user=svxlink group=svxlink threads=1 home=/var/www/genpw
WSGIScriptAlias /genpw /var/www/genpw/genpw.wsgi
<Directory /var/www/genpw>
WSGIProcessGroup genpw
WSGIApplicationGroup %{GLOBAL}
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
</IfModule>
----
[source,bash]
----
systemctl restart apache2
----
== Usage
Send a URL to the SvxLink node sysop that look something like the one below.
https://www.example.com/genpw?callsign=SM0XYZ
A new password will be generated each time the link is clicked. After the
SvxLink node sysop have clicked on the link to generate a password he should
send back the timestamp to the SvxReflector sysop in order for him to verify
that the password with the correct timestamp is used.
The SvxLink node sysop must not reload the page after generating a password
that is then used to configure the SvxLink node. Since the SvxReflector sysop
only see the latest generated password it will then be overwritten and thus
wrong.
The SvxReflector node sysop will run the getpw.py script on the webserver to retrieve the password to configure.
$ getpw.py SM0XYZ
SM0XYZ: "{"remote_addr": "11.22.33.44", "ts": "2021-02-14T19:51:30.291Z", "password": "!_2>4kGUHM7vorUctVJFaxZ!<!dzln"}"
The password will be removed from the database when accessed once.
It is also possible to list all callsigns in the database by running the script
above with no arguments.
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/python3
from flask import Flask, escape, request, make_response, jsonify, render_template_string
import secrets
import string
import dbm
import time
import json
import os
import math
page_template = '''
<!doctype html>
<html>
<head>
<title>SvxReflector Password Generator</title>
</head>
<body>
<h1>SvxReflector Password Generator</h1>
Copy the callsign and password configuration to your SvxLink ReflectorLogic
configuration. A new password is generated every time this page is reloaded so
when you have settled for a password, don't reload. Send the timestamp to the
SvxReflector administrator as a verification of that the correct password
generation is chosen.
<p/>
Timestamp: {{ data.ts }}
<p/>
<pre>
[ReflectorLogic]
...
CALLSIGN={{ data.callsign }}
AUTH_KEY="{{ data.password }}"
...
</pre>
<hr/>
</body>
</html>
'''
def random_pw_string(length):
alphabet = string.ascii_letters + string.digits \
+ '!#$%&*+:;<=>?_'
alphabet.translate({ord('"'): None, ord('\\'): None})
result_str = ''.join((secrets.choice(alphabet) for i in range(length)))
return result_str
app = Flask(__name__)
@app.route('/')
def genpw():
callsign = escape(request.args.get("callsign"))
if callsign == 'None' or len(callsign) == 0:
response = make_response('BAD REQUEST\n', 400)
response.mimetype = "text/plain"
else:
frac, epoch = math.modf(time.time())
frac_ms = int(1000 * frac)
ts = '%s.%03uZ' % (time.strftime('%Y-%m-%dT%H:%M:%S', \
time.gmtime(epoch)), frac_ms)
pw = random_pw_string(30)
data = {
'remote_addr': request.remote_addr,
'ts': ts,
'password': pw
}
os.umask(0o007)
with dbm.open('db/svxreflector-genpw', 'c', 0o660) as db:
db[callsign] = json.dumps(data)
data['callsign']=callsign
#print(data)
response = make_response(render_template_string(page_template, data=data), 200)
response.headers['Cache-Control'] = 'no-store'
return response
if __name__ == '__main__':
app.run(debug=False)
+1
View File
@@ -0,0 +1 @@
from genpw import app as application
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/python3
import dbm
import sys
import os
os.umask(0o007)
with dbm.open('/var/www/genpw/db/svxreflector-genpw', 'c', 0o660) as db:
if len(sys.argv) > 1:
callsign = sys.argv[1]
print(callsign + ': "' + db[callsign].decode() + '"')
del db[callsign]
else:
for k in db.keys():
print(k.decode() + ': ' + db[k].decode())
+300
View File
@@ -0,0 +1,300 @@
#!/bin/bash
set -euo pipefail
declare -r PKI_PATH=${PKI_PATH:-"/etc/svxlink/pki"}
declare -r CA_PATH=${CA_PATH:-"${PKI_PATH}/ca"}
declare -r CA_DB_PATH=${CA_DB_PATH:-"${CA_PATH}/db"}
declare -r CA_CSR_PATH=${CA_CSR_PATH:-"${CA_PATH}/ca.csr"}
declare -r CA_CRT_PATH=${CA_CRT_PATH:-"${CA_PATH}/ca.crt"}
declare -r CA_BUNDLE_PATH=${CA_BUNDLE_PATH:-"${PKI_PATH}/ca.pem"}
declare -r PENDING_CSRS_PATH=${PENDING_CSRS_PATH:-"${CA_PATH}/pending_csrs"}
declare -r CSRS_PATH=${CSRS_PATH:-"${CA_PATH}/csrs"}
declare -r CERTS_PATH=${CERTS_PATH:-"${CA_PATH}/certs"}
declare -r CRL_PATH=${CRL_PATH:-"${CA_PATH}/ca.crl"}
initialize_directories()
{
echo "--- Ensure that the PKI directory structure is present"
# Make sure that all CA directories have been created
for dirvar in CA_PATH PENDING_CSRS_PATH CSRS_PATH CERTS_PATH; do
dir="${!dirvar}"
if [[ ! -d "${dir}" ]]; then
echo "Creating directory '${dir}'"
mkdir -p "${dir}"
fi
done
echo
}
ca_conf()
{
cat <<-_EOF_
[ ca ]
default_ca = ca_default
[ ca_default ]
dir = ${CA_DB_PATH}
certs = \$dir
new_certs_dir = \$dir/ca.db.certs
database = \$dir/ca.db.index
serial = \$dir/ca.db.serial
RANDFILE = \$dir/ca.db.rand
certificate = ${CA_PATH}/ca.crt
private_key = ${CA_PATH}/ca.key
default_days = 365
default_crl_days = 30
default_md = sha256
preserve = no
policy = generic_policy
copy_extensions = copy
RANDFILE = ${CA_DB_PATH}/.rand
[ req ]
default_bits = 2048
distinguished_name = req_distinguished_name
string_mask = utf8only
default_md = sha256
x509_extensions = v3_ca
RANDFILE = ${CA_DB_PATH}/.rand
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default =
coutryName_min = 2
coutryName_max = 2
stateOrProvinceName = State or Province Name
stateOrProvinceName_default =
localityName = Locality Name (e.g. City)
localityName_default =
0.organizationName = Organization Name (e.g. Club/Callsign)
0.organizationName_default =
#organizationalUnitName = Organizational Unit Name
#organizationalUnitName_default =
commonName = Common Name (e.g. My Club CA)
emailAddress = Email Address
emailAddress_default =
[ v3_ca ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true
keyUsage = critical, digitalSignature, cRLSign, keyCertSign
[ generic_policy ]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
[ generic_cert ]
basicConstraints = CA:false
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
_EOF_
}
initialize_ca_db()
{
[[ ! -d "${CA_DB_PATH}" ]] || return 0
echo "--- Creating CA database under ${CA_DB_PATH}"
local ANS self_signed
while ! read -p 'Generate self-signed certificate (y/n)? ' ANS || \
! [[ "${ANS}" =~ ^[yYnN]$ ]] || \
! self_signed=$([[ "${ANS^}" = "Y" ]] && echo "true" || echo "false")
do :; done
mkdir -p "${CA_DB_PATH}/ca.db.certs"
touch "${CA_DB_PATH}/ca.db.index"
echo "1000" > "${CA_DB_PATH}/ca.db.serial"
#echo "unique_subject = no" > "${CA_DB_PATH}/ca.db.index.attr"
local openssl_args=(-newkey rsa:2048 -keyout "${CA_PATH}/ca.key")
if ${self_signed}; then
openssl_args+=(-x509 -days 7300 -out "${CA_CRT_PATH}")
else
openssl_args+=(-out "${CA_CSR_PATH}")
fi
openssl req -config <(ca_conf) "${openssl_args[@]}" &&:
if [[ $? -ne 0 ]]; then
echo "*** ERROR: Failed to create CA key and certificate"
return 1
fi
if ${self_signed}; then
[[ -e "${CA_BUNDLE_PATH}" ]] || cp "${CA_PATH}/ca.crt" "${CA_BUNDLE_PATH}"
else
cat <<-_EOF_
---------------------------------------------------------------------
Send the generated Certificate Signing Request (CSR) located in file
${CA_CSR_PATH}
to the Certificate Authority (CA) for signing. When the signed
certificate is returned by the CA, place it at these two locations:
${CA_CRT_PATH}
${CA_BUNDLE_PATH}
---------------------------------------------------------------------
_EOF_
fi
}
ca_cmd_config()
{
echo "--- CA OpenSSL configuration file"
ca_conf
}
ca_cmd_pending()
{
echo "--- Pending Certificate Signing Requests"
shopt -s nullglob
for csrfile in "${PENDING_CSRS_PATH}"/*.csr; do
#echo -n "${csrfile##*/}: "
openssl req -in "${csrfile}" -noout -subject | sed 's/^subject=//'
done
}
ca_cmd_rmpending()
{
local callsign="${1:-}"
if ! shift; then
echo "*** ERROR: Missing argument <CN/callsign> for 'rmpending' command."
echo
print_help
return 1
fi
echo "--- Remove Pending Certificate Signing Request: ${callsign}"
local csrfile="${PENDING_CSRS_PATH}/${callsign}.csr"
if [[ ! -e "${csrfile}" ]]; then
echo "*** ERROR: Could not find CSR file: ${csrfile}"
echo
ca_cmd_pending
return 1
fi
rm -f "${csrfile}"
}
ca_cmd_sign()
{
local callsign="${1:-}"
if ! shift; then
echo "*** ERROR: Missing argument <CN/callsign> for 'sign' command."
echo
print_help
return 1
fi
echo "--- Sign Certificate Signing Request for ${callsign}"
local csrfile="${PENDING_CSRS_PATH}/${callsign}.csr"
if [[ ! -e "${csrfile}" ]]; then
echo "*** ERROR: Could not find CSR file: ${csrfile}"
return 1
fi
openssl ca \
-config <(ca_conf) \
-out "${CERTS_PATH}/${callsign}.crt" \
-infiles "${csrfile}" &&:
if [[ $? -ne 0 ]]; then
echo "*** ERROR: Failed to sign ${csrfile}"
return 1
fi
mv "${csrfile}" "${CSRS_PATH}/${csrfile##*/}" &&:
if [[ $? -ne 0 ]]; then
echo "*** ERROR: Failed to move CSR from pending to signed"
return 1
fi
}
ca_cmd_revoke()
{
local callsign="${1:-}"
if ! shift; then
echo "*** ERROR: Missing argument <CN/callsign> for 'revoke' command."
echo
print_help
return 1
fi
echo "--- Revoke Certificate for ${callsign}"
local crtfile="${CERTS_PATH}/${callsign}.crt"
if [[ ! -e "${crtfile}" ]]; then
echo "*** ERROR: Could not find certificate file: ${crtfile}"
return 1
fi
openssl ca \
-config <(ca_conf) \
-revoke "${crtfile}" \
-crl_reason superseded &&:
if [[ $? -ne 0 ]]; then
echo "*** ERROR: Failed to revoke ${crtfile}"
return 1
fi
openssl ca \
-config <(ca_conf) \
-gencrl \
-out "${CRL_PATH}"
}
run_command()
{
local cmd_name="$1"; shift
local cmd_func="ca_cmd_${cmd_name}"
if ! declare -F "${cmd_func}" &>/dev/null; then
echo "*** ERROR: No such command: '${cmd_name}'"
return 1
fi
"${cmd_func}" "$@"
}
print_help()
{
cat <<-_EOF_
Usage: ${0##*/} <command> [command args]
Commands:
config -- Print OpenSSL configuration file
pending -- List pending certificate signing requests
rmpending <CN/callsign> -- Remove a pending certificate signing request
sign <CN/callsign> -- Sign a pending certificate signing request
revoke <CN/callsign> -- Revoke a certificate
_EOF_
}
main()
{
if [[ $# -lt 1 ]]; then
print_help
exit 1
fi
local cmd="$1"; shift
initialize_directories
initialize_ca_db
run_command "${cmd}" "$@"
}
main "$@"
# vim: set filetype=sh:
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env python3
import requests
import curses
import time
import sys
import traceback
from collections import defaultdict
# API endpoint
URL = "http://localhost:8080/status"
if len(sys.argv) > 1:
URL = sys.argv[1]
def print_error(stdscr, msg):
stdscr.erase()
stdscr.addstr(0, 0, msg)
stdscr.refresh()
def draw_status(stdscr):
# Get SvxReflector status
try:
r = requests.get(url = URL)
except requests.exceptions.ConnectionError as e:
print_error(stdscr, '*** ERROR: ' + str(e))
return
if r.status_code != 200:
print_error(stdscr, '*** ERROR: Could not get ' + URL)
return
# Extract data in JSON format
data = r.json()
# Get terminal size
rows, columns = stdscr.getmaxyx()
# Row format for all table rows
row_fmt = "%-9s | %8s | %15s | %3s | %s"
# Sort nodes on talkgroup
tg2nodes = defaultdict(list)
for callsign in sorted(data['nodes'].keys()):
node = data['nodes'][callsign]
tg = int(node['tg'])
node['callsign'] = callsign
tg2nodes[tg].append(node)
# Print header line
header = row_fmt % ("Callsign", "TG#", "RX", "Lev", "Monitored TGs")
right_txt = "| %d | %s" % (len(data['nodes']), time.ctime())
nspaces = int(columns) - len(right_txt) - len(header)
if nspaces > 0:
header = header + (' ' * nspaces) + right_txt
stdscr.addstr(0, 0, header, curses.color_pair(3) | curses.A_REVERSE | curses.A_BOLD)
# Print all node lines
def print_node_lines():
line = 1
for tg in sorted(tg2nodes.keys(), reverse=True):
node_list = tg2nodes[tg]
for node in node_list:
callsign = node['callsign']
tg = str(node['tg'])
if 'restrictedTG' in node and bool(node['restrictedTG']):
tg = "*" + tg
monitored_tgs = " ".join(str(tg) for tg in node['monitoredTGs'])
rx_name = ''
siglev = ''
if 'qth' in node and isinstance(node['qth'], list):
for qth in node['qth']:
qth_name = ''
if 'name' in qth:
qth_name = ' ' + qth['name']
if 'rx' in qth:
for rx_id in qth['rx']:
rx = qth['rx'][rx_id]
if 'active' in rx and rx['active']:
rx_name = rx['name'] + qth_name
siglev = rx['siglev']
rx_name = rx_name[0:15]
attrs = curses.color_pair(2)
if node['isTalker']:
attrs = curses.color_pair(1)
stdscr.addnstr(line, 0, row_fmt % (callsign, tg, rx_name, siglev, monitored_tgs), int(columns)-1, attrs)
stdscr.clrtoeol()
if line >= rows-1:
return
line = line + 1
print_node_lines()
stdscr.clrtobot()
stdscr.refresh()
def main(stdscr):
curses.curs_set(False)
curses.use_default_colors()
curses.init_pair(1, curses.COLOR_RED, -1)
curses.init_pair(2, curses.COLOR_GREEN, -1)
curses.init_pair(3, curses.COLOR_YELLOW, -1)
stdscr.timeout(500)
while True:
try:
draw_status(stdscr)
except:
stdscr.erase()
stdscr.addstr(0, 0, traceback.format_exc())
stdscr.refresh()
# Read command. Will timeout after the time specified above.
cmd = stdscr.getch()
if cmd == ord('q'):
break;
try:
curses.wrapper(main)
except KeyboardInterrupt:
pass
+101
View File
@@ -0,0 +1,101 @@
###################################################################
#
# Configuration file for the SvxReflector SvxLink conference node
#
###################################################################
[GLOBAL]
#CFG_DIR=svxreflector.d
TIMESTAMP_FORMAT="%c"
LISTEN_PORT=5300
#SQL_TIMEOUT=600
#SQL_TIMEOUT_BLOCKTIME=60
#CODECS=OPUS
TG_FOR_V1_CLIENTS=999
#LOCAL_PREFIX=1
#RANDOM_QSY_RANGE=12399:100
#HTTP_SRV_PORT=8080
COMMAND_PTY=/dev/shm/reflector_ctrl
#ACCEPT_CALLSIGN="[A-Z0-9][A-Z]{0,2}\\d[A-Z0-9]{0,3}[A-Z](?:-[A-Z0-9]{1,3})?"
#REJECT_CALLSIGN=""
#ACCEPT_CERT_EMAIL="\\w+(?:[-._+]\\w+)*@\\w+(?:\\.\\w+)*"
#CERT_PKI_DIR=pki/
#CERT_CA_BUNDLE=ca-bundle.crt
#CERT_CA_KEYS_DIR=private/
#CERT_CA_PENDING_CSRS_DIR=pending_csrs/
#CERT_CA_CSRS_DIR=csrs/
#CERT_CA_CERTS_DIR=certs/
CERT_CA_HOOK=@SVX_SHARE_INSTALL_DIR@/ca-hook.py
[ROOT_CA]
#KEYFILE=svxreflector_root_ca.key
#CRTFILE=svxreflector_root_ca.crt
#COMMON_NAME=SvxReflector Root CA
#ORG_UNIT=SvxLink
#ORG=MyOrg
#LOCALITY=MyTown
#STATE=StateOrProvince
#COUNTRY=XX
#EMAIL_ADDRESS=sysop@svxlink.example.org
[ISSUING_CA]
#KEYFILE=svxreflector_issuing_ca.key
#CSRFILE=svxreflector_issuing_ca.csr
#CRTFILE=svxreflector_issuing_ca.crt
#COMMON_NAME=SvxReflector Issuing CA
#ORG_UNIT=SvxLink
#ORG=MyOrg
#LOCALITY=MyTown
#STATE=StateOrProvince
#COUNTRY=XX
#EMAIL_ADDRESS=sysop@svxlink.example.org
[SERVER_CERT]
#KEYFILE=svxreflector.key
#CSRFILE=svxreflector.csr
#CRTFILE=svxreflector.crt
#COMMON_NAME=svxreflector.example.org
#ORG_UNIT=SvxLink
#ORG=MyOrg
#LOCALITY=MyTown
#STATE=StateOrProvince
#COUNTRY=XX
#SUBJECT_ALT_NAME=DNS:public-hostname.example.org,IP:172.17.1.42
#EMAIL_ADDRESS=sysop@svxlink.example.org
[USERS]
#SM0ABC-1=MyNodes
#SM0ABC-2=MyNodes
#SM3XYZ=SM3XYZ
[PASSWORDS]
#MyNodes="Change this key now!"
#SM3XYZ="A strong password"
#[TG#9999]
#AUTO_QSY_AFTER=300
#ALLOW=S[A-M]\\\\d.*|LA8PV
#ALLOW_MONITOR=S[A-M]3.*
#SHOW_ACTIVITY=0
# Trunk links to peer SvxReflector instances (prefix-based TG routing).
#
# Each reflector owns all TGs whose decimal representation starts with
# LOCAL_PREFIX. For example, LOCAL_PREFIX=1 means this reflector is
# authoritative for TGs 1, 10, 100, 1000, 12345, etc.
#
# Add LOCAL_PREFIX to the [GLOBAL] section, then add one [TRUNK_x] section
# per peer. REMOTE_PREFIX declares which TG prefix the peer owns.
#
# Example for a two-reflector mesh:
# Reflector A: LOCAL_PREFIX=1, [TRUNK_2] with REMOTE_PREFIX=2
# Reflector B: LOCAL_PREFIX=2, [TRUNK_1] with REMOTE_PREFIX=1
#
#LOCAL_PREFIX=1
#[TRUNK_2]
#HOST=reflector-b.example.com
#PORT=5302
#SECRET=change_this_shared_secret
#REMOTE_PREFIX=2
+587
View File
@@ -0,0 +1,587 @@
/**
@file svxreflector.cpp
@brief Main source file for the SvxReflector application
@author Tobias Blomberg / SM0SVX
@date 2017-02-11
The SvxReflector application is a central hub used to connect multiple SvxLink
nodes together.
\verbatim
SvxReflector - An audio reflector for connecting SvxLink Servers
Copyright (C) 2003-2025 Tobias Blomberg / SM0SVX
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\endverbatim
*/
/****************************************************************************
*
* System Includes
*
****************************************************************************/
#include <locale.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <grp.h>
#include <pwd.h>
#include <dirent.h>
#include <termios.h>
#include <errno.h>
#include <popt.h>
#include <sigc++/sigc++.h>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <iomanip>
/****************************************************************************
*
* Project Includes
*
****************************************************************************/
#include <AsyncCppApplication.h>
#include <AsyncFdWatch.h>
#include <AsyncConfig.h>
#include <config.h>
#include <LogWriter.h>
/****************************************************************************
*
* Local Includes
*
****************************************************************************/
#include "version/SVXREFLECTOR.h"
#include "Reflector.h"
/****************************************************************************
*
* Namespaces to use
*
****************************************************************************/
using namespace std;
using namespace Async;
/****************************************************************************
*
* Defines & typedefs
*
****************************************************************************/
#define PROGRAM_NAME "SvxReflector"
/****************************************************************************
*
* Local class definitions
*
****************************************************************************/
/****************************************************************************
*
* Prototypes
*
****************************************************************************/
static void parse_arguments(int argc, const char **argv);
static void stdinHandler(FdWatch *w);
static void sighup_handler(int signal);
static void sigterm_handler(int signal);
static void handle_unix_signal(int signum);
/****************************************************************************
*
* Exported Global Variables
*
****************************************************************************/
/****************************************************************************
*
* Local Global Variables
*
****************************************************************************/
namespace {
char* pidfile_name = nullptr;
char* logfile_name = nullptr;
char* runasuser = nullptr;
char* config = nullptr;
int daemonize = 0;
int quiet = 0;
FdWatch* stdin_watch = 0;
LogWriter logwriter;
};
/****************************************************************************
*
* MAIN
*
****************************************************************************/
/*
*----------------------------------------------------------------------------
* Function: main
* Purpose: Start everything...
* Input: argc - The number of arguments passed to this program
* (including the program name).
* argv - The arguments passed to this program. argv[0] is the
* program name.
* Output: Return 0 on success, else non-zero.
* Author: Tobias Blomberg, SM0SVX
* Created: 2017-02-11
* Remarks:
* Bugs:
*----------------------------------------------------------------------------
*/
int main(int argc, const char *argv[])
{
setlocale(LC_ALL, "");
CppApplication app;
app.catchUnixSignal(SIGHUP);
app.catchUnixSignal(SIGINT);
app.catchUnixSignal(SIGTERM);
app.unixSignalCaught.connect(sigc::ptr_fun(&handle_unix_signal));
parse_arguments(argc, const_cast<const char **>(argv));
if (daemonize && (daemon(1, 0) == -1))
{
perror("daemon");
exit(1);
}
if (quiet || (logfile_name != 0))
{
int devnull = open("/dev/null", O_RDWR);
if (devnull == -1)
{
perror("open(/dev/null)");
exit(1);
}
if (quiet)
{
/* Redirect stdout to /dev/null */
dup2(devnull, STDOUT_FILENO);
}
if (logfile_name != 0)
{
logwriter.setDestinationName(logfile_name);
if (!quiet)
{
logwriter.redirectStdout();
}
logwriter.redirectStderr();
logwriter.start();
/* Redirect stdin to /dev/null */
if (dup2(devnull, STDIN_FILENO) == -1)
{
perror("dup2(stdin)");
exit(1);
}
}
close(devnull);
}
if (pidfile_name != NULL)
{
FILE *pidfile = fopen(pidfile_name, "w");
if (pidfile == 0)
{
char err[256];
snprintf(err, sizeof(err), "fopen(\"%s\")", pidfile_name);
perror(err);
fflush(stderr);
exit(1);
}
fprintf(pidfile, "%d\n", getpid());
fclose(pidfile);
}
const char *home_dir = 0;
if (runasuser != NULL)
{
// Setup supplementary group IDs
if (initgroups(runasuser, getgid()))
{
perror("initgroups");
exit(1);
}
struct passwd *passwd = getpwnam(runasuser);
if (passwd == NULL)
{
perror("getpwnam");
exit(1);
}
if (setgid(passwd->pw_gid) == -1)
{
perror("setgid");
exit(1);
}
if (setuid(passwd->pw_uid) == -1)
{
perror("setuid");
exit(1);
}
home_dir = passwd->pw_dir;
}
if (home_dir == 0)
{
home_dir = getenv("HOME");
}
if (home_dir == 0)
{
home_dir = ".";
}
Config cfg;
string cfg_filename;
if (config != NULL)
{
cfg_filename = string(config);
if (!cfg.open(cfg_filename))
{
cerr << "*** ERROR: Could not open configuration file: "
<< config << endl;
exit(1);
}
}
else
{
cfg_filename = string(home_dir);
cfg_filename += "/.svxlink/svxreflector.conf";
if (!cfg.open(cfg_filename))
{
cfg_filename = SVX_SYSCONF_INSTALL_DIR "/svxreflector.conf";
if (!cfg.open(cfg_filename))
{
cerr << "*** ERROR: Could not open configuration file";
if (errno != 0)
{
cerr << " (" << strerror(errno) << ")";
}
cerr << ".\n";
cerr << "Tried the following paths:\n"
<< "\t" << home_dir << "/.svxlink/svxreflector.conf\n"
<< "\t" SVX_SYSCONF_INSTALL_DIR "/svxreflector.conf\n"
<< "Possible reasons for failure are: None of the files exist,\n"
<< "you do not have permission to read the file or there was a\n"
<< "syntax error in the file.\n";
exit(1);
}
}
}
string main_cfg_filename(cfg_filename);
std::string main_cfg_dir = ".";
auto slash_pos = main_cfg_filename.rfind('/');
if (slash_pos != std::string::npos)
{
main_cfg_dir = main_cfg_filename.substr(0, slash_pos);
}
string cfg_dir;
if (cfg.getValue("GLOBAL", "CFG_DIR", cfg_dir))
{
if (cfg_dir[0] != '/')
{
cfg_dir = main_cfg_dir + "/" + cfg_dir;
}
DIR *dir = opendir(cfg_dir.c_str());
if (dir == NULL)
{
cerr << "*** ERROR: Could not read from directory spcified by "
<< "configuration variable GLOBAL/CFG_DIR=" << cfg_dir << endl;
exit(1);
}
struct dirent *dirent;
while ((dirent = readdir(dir)) != NULL)
{
char *dot = strrchr(dirent->d_name, '.');
if ((dot == NULL) || (dirent->d_name[0] == '.') ||
(strcmp(dot, ".conf") != 0))
{
continue;
}
cfg_filename = cfg_dir + "/" + dirent->d_name;
if (!cfg.open(cfg_filename))
{
cerr << "*** ERROR: Could not open configuration file: "
<< cfg_filename << endl;
exit(1);
}
}
if (closedir(dir) == -1)
{
cerr << "*** ERROR: Error closing directory specified by"
<< "configuration variable GLOBAL/CFG_DIR=" << cfg_dir << endl;
exit(1);
}
}
std::string tstamp_format = "%c";
cfg.getValue("GLOBAL", "TIMESTAMP_FORMAT", tstamp_format);
logwriter.setTimestampFormat(tstamp_format);
cout << PROGRAM_NAME " v" SVXREFLECTOR_VERSION
" Copyright (C) 2003-2025 Tobias Blomberg / SM0SVX\n";
cout << "Modified with server-to-server trunk support by IW1GEU.\n\n";
cout << PROGRAM_NAME " comes with ABSOLUTELY NO WARRANTY. "
"This is free software, and you are\n";
cout << "welcome to redistribute it in accordance with the "
"terms and conditions in the\n";
cout << "GNU GPL (General Public License) version 2 or later.\n";
cout << "\nUsing configuration file: " << main_cfg_filename << endl;
struct termios org_termios = {0};
if (logfile_name == 0)
{
struct termios termios;
tcgetattr(STDIN_FILENO, &org_termios);
termios = org_termios;
termios.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &termios);
stdin_watch = new FdWatch(STDIN_FILENO, FdWatch::FD_WATCH_RD);
stdin_watch->activity.connect(sigc::ptr_fun(&stdinHandler));
}
Reflector ref;
if (ref.initialize(cfg))
{
std::cout << "NOTICE: Initialization done. Starting main application."
<< std::endl;
app.exec();
}
else
{
cerr << ":-(" << endl;
}
if (stdin_watch != 0)
{
delete stdin_watch;
tcsetattr(STDIN_FILENO, TCSANOW, &org_termios);
}
return 0;
} /* main */
/****************************************************************************
*
* Functions
*
****************************************************************************/
/*
*----------------------------------------------------------------------------
* Function: parse_arguments
* Purpose: Parse the command line arguments.
* Input: argc - Number of arguments in the command line
* argv - Array of strings with the arguments
* Output: Returns 0 if all is ok, otherwise -1.
* Author: Tobias Blomberg, SM0SVX
* Created: 2000-06-13
* Remarks:
* Bugs:
*----------------------------------------------------------------------------
*/
static void parse_arguments(int argc, const char **argv)
{
int print_version = 0;
poptContext optCon;
const struct poptOption optionsTable[] =
{
POPT_AUTOHELP
{"pidfile", 0, POPT_ARG_STRING, &pidfile_name, 0,
"Specify the name of the pidfile to use", "<filename>"},
{"logfile", 0, POPT_ARG_STRING, &logfile_name, 0,
"Specify the logfile to use (stdout and stderr)", "<filename>"},
{"runasuser", 0, POPT_ARG_STRING, &runasuser, 0,
"Specify the user to run SvxLink as", "<username>"},
{"config", 0, POPT_ARG_STRING, &config, 0,
"Specify the configuration file to use", "<filename>"},
/*
{"int_arg", 'i', POPT_ARG_INT, &int_arg, 0,
"Description of int argument", "<an int>"},
*/
{"daemon", 0, POPT_ARG_NONE, &daemonize, 0,
"Start " PROGRAM_NAME " as a daemon", NULL},
{"version", 0, POPT_ARG_NONE, &print_version, 0,
"Print the application version string", NULL},
{NULL, 0, 0, NULL, 0}
};
int err;
//const char *arg = NULL;
//int argcnt = 0;
optCon = poptGetContext(PROGRAM_NAME, argc, argv, optionsTable, 0);
poptReadDefaultConfig(optCon, 0);
err = poptGetNextOpt(optCon);
if (err != -1)
{
fprintf(stderr, "\t%s: %s\n",
poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
poptStrerror(err));
exit(1);
}
/*
printf("string_arg = %s\n", string_arg);
printf("int_arg = %d\n", int_arg);
printf("bool_arg = %d\n", bool_arg);
*/
/* Parse arguments that do not begin with '-' (leftovers) */
/*
arg = poptGetArg(optCon);
while (arg != NULL)
{
printf("arg %2d = %s\n", ++argcnt, arg);
arg = poptGetArg(optCon);
}
*/
poptFreeContext(optCon);
if (print_version)
{
std::cout << SVXREFLECTOR_VERSION << std::endl;
exit(0);
}
} /* parse_arguments */
static void stdinHandler(FdWatch *w)
{
char buf[1];
int cnt = ::read(STDIN_FILENO, buf, 1);
if (cnt == -1)
{
fprintf(stderr, "*** ERROR: Reading from stdin failed\n");
Application::app().quit();
return;
}
else if (cnt == 0)
{
/* Stdin file descriptor closed */
delete stdin_watch;
stdin_watch = 0;
return;
}
switch (toupper(buf[0]))
{
case 'Q':
Application::app().quit();
break;
case '\n':
putchar('\n');
break;
default:
break;
}
} /* stdinHandler */
static void sighup_handler(int signal)
{
if (logfile_name == 0)
{
cout << "Ignoring SIGHUP\n";
return;
}
std::cout << "SIGHUP received" << std::endl;
logwriter.reopenLogfile();
} /* sighup_handler */
static void sigterm_handler(int signal)
{
const char *signame = 0;
switch (signal)
{
case SIGTERM:
signame = "SIGTERM";
break;
case SIGINT:
signame = "SIGINT";
break;
default:
signame = "Unknown signal";
break;
}
std::cout << "\nNOTICE: " << signame
<< " received. Shutting down application..."
<< std::endl;
Application::app().quit();
} /* sigterm_handler */
static void handle_unix_signal(int signum)
{
switch (signum)
{
case SIGHUP:
sighup_handler(signum);
break;
case SIGINT:
case SIGTERM:
sigterm_handler(signum);
break;
}
} /* handle_unix_signal */
/*
* This file has not been truncated
*/