/** @file ReflectorClient.cpp @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 */ /**************************************************************************** * * System Includes * ****************************************************************************/ #include #include #include #include #include #include #include #include /**************************************************************************** * * Project Includes * ****************************************************************************/ #include #include #include #include #include #include /**************************************************************************** * * Local Includes * ****************************************************************************/ #include "ReflectorClient.h" #include "Reflector.h" #include "TGHandler.h" #include "RedisStore.h" #include /**************************************************************************** * * Namespaces to use * ****************************************************************************/ using namespace std; using namespace Async; /**************************************************************************** * * Defines & typedefs * ****************************************************************************/ #define RENEW_AFTER 2/3 /**************************************************************************** * * Local class definitions * ****************************************************************************/ /**************************************************************************** * * Prototypes * ****************************************************************************/ /**************************************************************************** * * Exported Global Variables * ****************************************************************************/ /**************************************************************************** * * Local Global Variables * ****************************************************************************/ ReflectorClient::ClientMap ReflectorClient::client_map; ReflectorClient::ClientSrcMap ReflectorClient::client_src_map; ReflectorClient::ClientCallsignMap ReflectorClient::client_callsign_map; std::mt19937 ReflectorClient::id_gen(std::random_device{}()); ReflectorClient::ClientIdRandomDist ReflectorClient::id_dist( CLIENT_ID_MIN, CLIENT_ID_MAX); /**************************************************************************** * * Public member functions * ****************************************************************************/ ReflectorClient* ReflectorClient::lookup(const ClientId& id) { auto it = client_map.find(id); if (it == client_map.end()) { return nullptr; } return it->second; } /* ReflectorClient::lookup */ ReflectorClient* ReflectorClient::lookup(const ClientSrc& src) { auto it = client_src_map.find(src); if (it == client_src_map.end()) { return nullptr; } return it->second; } /* ReflectorClient::lookup */ ReflectorClient* ReflectorClient::lookup(const std::string& cs) { auto it = client_callsign_map.find(cs); if (it == client_callsign_map.end()) { return nullptr; } return it->second; } /* ReflectorClient::lookup */ void ReflectorClient::cleanup(void) { auto client_map_copy = client_map; for (const auto& item : client_map_copy) { delete item.second; } assert(client_map.size() == 0); } /* ReflectorClient::cleanup */ bool ReflectorClient::TgFilter::operator()(ReflectorClient* client) const { //cout << "m_tg=" << m_tg << " client_tg=" // << TGHandler::instance()->TGForClient(client) << endl; return m_tg == TGHandler::instance()->TGForClient(client); } bool ReflectorClient::PassiveObserverFilter::operator()( ReflectorClient* client) const { return client->m_current_tg == 0; } /* ReflectorClient::PassiveObserverFilter::operator() */ namespace { // Look up the earliest of (local talker start, trunk talker start) for a TG. // Returns true iff at least one was set. Used by EarliestMonitorTalkerFilter. bool startTimeForTG(uint32_t tg, struct timeval& out) { TGHandler* h = TGHandler::instance(); struct timeval local_ts, trunk_ts; bool has_local = h->talkerStartTimeForTG(tg, local_ts); bool has_trunk = h->trunkTalkerStartTimeForTG(tg, trunk_ts); if (has_local && has_trunk) { out = timercmp(&local_ts, &trunk_ts, <) ? local_ts : trunk_ts; return true; } if (has_local) { out = local_ts; return true; } if (has_trunk) { out = trunk_ts; return true; } return false; } } // namespace bool ReflectorClient::EarliestMonitorTalkerFilter::operator()( ReflectorClient* client) const { if (client->m_monitored_tgs.count(m_tg) == 0) { return false; } struct timeval m_tg_ts; if (!startTimeForTG(m_tg, m_tg_ts)) { // m_tg has never had a talker recorded — nothing to deliver. return false; } uint32_t earliest_tg = m_tg; struct timeval earliest_ts = m_tg_ts; TGHandler* h = TGHandler::instance(); for (uint32_t tg : client->m_monitored_tgs) { if (tg == m_tg) { continue; } bool active = (h->talkerForTG(tg) != nullptr) || h->hasTrunkTalker(tg); if (!active) { continue; } struct timeval ts; if (!startTimeForTG(tg, ts)) { continue; } bool earlier = timercmp(&ts, &earliest_ts, <); bool same = !earlier && ts.tv_sec == earliest_ts.tv_sec && ts.tv_usec == earliest_ts.tv_usec; if (earlier || (same && tg < earliest_tg)) { earliest_tg = tg; earliest_ts = ts; } } return earliest_tg == m_tg; } /* ReflectorClient::EarliestMonitorTalkerFilter::operator() */ ReflectorClient::ReflectorClient(Reflector *ref, Async::FramedTcpConnection *con, Async::Config *cfg) : m_con(con), m_con_state(STATE_EXPECT_PROTO_VER), m_disc_timer(10000, Timer::TYPE_ONESHOT, false), m_client_id(newClientId(this)), m_remote_udp_port(0), m_cfg(cfg), /*m_next_udp_tx_seq(0),*/ m_next_udp_rx_seq(0), m_heartbeat_timer(1000, Timer::TYPE_PERIODIC), m_heartbeat_tx_cnt(HEARTBEAT_TX_CNT_RESET), m_heartbeat_rx_cnt(HEARTBEAT_RX_CNT_RESET), m_udp_heartbeat_tx_cnt(UDP_HEARTBEAT_TX_CNT_RESET), m_udp_heartbeat_rx_cnt(UDP_HEARTBEAT_RX_CNT_RESET), m_reflector(ref), m_blocktime(0), m_remaining_blocktime(0), m_current_tg(0), m_udp_cipher_iv_cntr(0) { m_con->setMaxRxFrameSize(ReflectorMsg::MAX_PREAUTH_FRAME_SIZE); m_con->setMaxTxFrameSize(ReflectorMsg::MAX_POSTAUTH_FRAME_SIZE); m_con->sslConnectionReady.connect( sigc::mem_fun(*this, &ReflectorClient::onSslConnectionReady)); m_con->frameReceived.connect( sigc::mem_fun(*this, &ReflectorClient::onFrameReceived)); m_disc_timer.expired.connect( sigc::mem_fun(*this, &ReflectorClient::onDiscTimeout)); m_heartbeat_timer.expired.connect( sigc::mem_fun(*this, &ReflectorClient::handleHeartbeat)); m_renew_cert_timer.expired.connect(sigc::hide( sigc::mem_fun(*this, &ReflectorClient::renewClientCertificate))); string codecs; if (m_cfg->getValue("GLOBAL", "CODECS", codecs)) { SvxLink::splitStr(m_supported_codecs, codecs, ","); } if (m_supported_codecs.size() > 1) { m_supported_codecs.erase(m_supported_codecs.begin()+1, m_supported_codecs.end()); geulog::warn("client", "The GLOBAL/CODECS configuration variable can only " "take one codec at the moment. Using the first one: \"", m_supported_codecs.front(), "\""); } else if (m_supported_codecs.empty()) { string codec = "GSM"; if (AudioDecoder::isAvailable("OPUS") && AudioEncoder::isAvailable("OPUS")) { codec = "OPUS"; } else if (AudioDecoder::isAvailable("SPEEX") && AudioEncoder::isAvailable("SPEEX")) { codec = "SPEEX"; } m_supported_codecs.push_back(codec); } } /* ReflectorClient::ReflectorClient */ ReflectorClient::~ReflectorClient(void) { m_status = nullptr; auto client_it = client_map.find(m_client_id); assert(client_it != client_map.end()); client_map.erase(client_it); client_src_map.erase(m_client_src); if (!m_callsign.empty()) { client_callsign_map.erase(m_callsign); } TGHandler::instance()->removeClient(this); } /* ReflectorClient::~ReflectorClient */ void ReflectorClient::setRemoteUdpSource(const ReflectorClient::ClientSrc& src) { assert(m_remote_udp_port == 0); m_remote_udp_port = src.second; if (m_client_proto_ver >= ProtoVer(3, 0)) { m_client_src = src; client_src_map[src] = this; } } /* ReflectorClient::setRemoteUdpSource */ int ReflectorClient::sendMsg(const ReflectorMsg& msg) { errno = 0; if (((m_con_state != STATE_CONNECTED) && (msg.type() >= 100)) || !m_con->isConnected()) { errno = ENOTCONN; } ostringstream ss; if (errno == 0) { m_heartbeat_tx_cnt = HEARTBEAT_TX_CNT_RESET; ReflectorMsg header(msg.type()); if (!header.pack(ss) || !msg.pack(ss)) { geulog::error("client", "Failed to pack TCP message"); errno = EBADMSG; } } if (errno == 0) { auto ret = m_con->write(ss.str().data(), ss.str().size()); if (ret >= 0) { return ret; } } geulog::debug("client", "[", m_con->remoteHost(), ":", m_con->remotePort(), "] sendMsg: write failed: ", strerror(errno), " (msg type ", msg.type(), ")"); disconnect(); return -1; } /* ReflectorClient::sendMsg */ void ReflectorClient::udpMsgReceived(const ReflectorUdpMsg &header) { m_udp_heartbeat_rx_cnt = UDP_HEARTBEAT_RX_CNT_RESET; if ((m_blocktime > 0) && (header.type() == MsgUdpAudio::TYPE)) { m_remaining_blocktime = m_blocktime; } } /* ReflectorClient::udpMsgReceived */ void ReflectorClient::sendUdpMsg(const ReflectorUdpMsg &msg) { if (remoteUdpPort() == 0) { return; } m_udp_heartbeat_tx_cnt = UDP_HEARTBEAT_TX_CNT_RESET; (void)m_reflector->sendUdpDatagram(this, msg); } /* ReflectorClient::sendUdpMsg */ void ReflectorClient::setBlock(unsigned blocktime) { if (blocktime > 0) { geulog::info("client", m_callsign, ": Blocking talker for ", blocktime, " seconds"); } else if (m_blocktime > 0) { geulog::info("client", m_callsign, ": Unblocking talker"); } m_blocktime = blocktime; m_remaining_blocktime = blocktime; } /* ReflectorClient::setBlock */ void ReflectorClient::updateIsTalker(void) { if (m_status != nullptr) { auto talker = TGHandler::instance()->talkerForTG(m_current_tg); (*m_status)["isTalker"] = ( TGHandler::instance()->showActivity(m_current_tg) && (talker == this) ); } } /* ReflectorClient:;updateIsTalker */ std::vector ReflectorClient::udpCipherIV(void) const { return UdpCipher::IV{udpCipherIVRand(), 0, m_udp_cipher_iv_cntr}; } /* ReflectorClient::udpCipherIV */ void ReflectorClient::certificateUpdated(Async::SslX509& cert) { if (m_con_state == STATE_CONNECTED) { //sendMsg(MsgClientCert(cert.pem())); sendClientCert(cert); } } /* ReflectorClient::certificateUpdated */ /**************************************************************************** * * Protected member functions * ****************************************************************************/ /**************************************************************************** * * Private member functions * ****************************************************************************/ ReflectorClient::ClientId ReflectorClient::newClientId(ReflectorClient* client) { assert(client_map.size() < (static_cast(CLIENT_ID_MAX)-CLIENT_ID_MIN+1)); ClientId id = id_dist(id_gen); while (client_map.count(id) > 0) { id = (id < CLIENT_ID_MAX) ? id+1 : CLIENT_ID_MIN; } client_map[id] = client; return id; } /* ReflectorClient::newClientId */ void ReflectorClient::onSslConnectionReady(TcpConnection *con) { //std::cout << "### ReflectorClient::onSslConnectionReady" << std::endl; if (m_con_state != STATE_EXPECT_SSL_CON_READY) { geulog::error("client", "[", m_con->remoteHost(), ":", m_con->remotePort(), "] SSL connection ready event unexpected"); disconnect(); return; } //m_con->setMaxRxFrameSize(ReflectorMsg::MAX_POST_SSL_SETUP_FRAME_SIZE); Async::SslX509 peer_cert(con->sslPeerCertificate()); if (peer_cert.isNull()) { geulog::info("client", m_con->remoteHost(), ":", m_con->remotePort(), ": No client certificate. Requesting Certificate " "Signing Request from client."); sendMsg(MsgClientCsrRequest()); m_con_state = STATE_EXPECT_CSR; return; //MsgAuthChallenge challenge_msg; //if (challenge_msg.challenge() == nullptr) //{ // disconnect(); // return; //} //memcpy(m_auth_challenge, challenge_msg.challenge(), // MsgAuthChallenge::LENGTH); //sendMsg(challenge_msg); //m_con_state = STATE_EXPECT_AUTH_RESPONSE; //return; } geulog::info("client", "------------- Client Certificate --------------"); peer_cert.print(); geulog::info("client", "-----------------------------------------------"); std::string callsign = peer_cert.commonName(); if (!m_reflector->callsignOk(callsign)) { geulog::warn("client", "[", m_con->remoteHost(), ":", m_con->remotePort(), "] client certificate has invalid CN (callsign)"); disconnect(); return; } // Set cert renewal timer to expire one minute after the actual renewal // time to avoid a race condition. Also delay renewal to at least 10 // minutes after node connection to reduce problems with renewal loops. // Renewal loops may occur if the client does not accept a new certificate // for some reason and upon reconnection continue to use the old // certificate, in which case the reflector will send the new cert again, // and so on. This may happen if the real-time clock is not correctly set // on the node. time_t renew_time = std::max( std::time(NULL) + 10*60, Reflector::timeToRenewCert(peer_cert) + 60); m_renew_cert_timer.setTimeout(renew_time); m_renew_cert_timer.start(); geulog::info("client", callsign, ": ", peer_cert.subjectNameString()); connectionAuthenticated(callsign); } /* ReflectorClient::onSslConnectionReady */ void ReflectorClient::onFrameReceived(FramedTcpConnection *con, std::vector& data) { if ((m_con_state == STATE_DISCONNECTED) || (m_con_state == STATE_EXPECT_DISCONNECT)) { return; } int len = data.size(); assert(len >= 0); auto buf = reinterpret_cast(data.data()); stringstream ss; ss.write(buf, len); std::stringstream idss; if (m_callsign.empty()) { idss << m_con->remoteHost() << ":" << m_con->remotePort(); } else { idss << m_callsign; } ReflectorMsg header; if (!header.unpack(ss)) { geulog::error("client", "[", idss.str(), "]: Unpacking failed for TCP message header"); sendError("Protocol error"); return; } if ((m_con_state != STATE_CONNECTED) && (header.type() >= 100)) { // FIXME: This should really be an error and the client should be // disconnected but it will cause too much problems in existing // misbeaving clients at the moment. geulog::warn("client", "[", idss.str(), "]: User message ", header.type(), " received in unauthenticated state"); //sendError("Protocol error"); // Do not reset heartbeat — unauthenticated clients must not stay alive return; } m_heartbeat_rx_cnt = HEARTBEAT_RX_CNT_RESET; switch (header.type()) { case MsgHeartbeat::TYPE: break; case MsgProtoVer::TYPE: handleMsgProtoVer(ss); break; case MsgCABundleRequest::TYPE: handleMsgCABundleRequest(ss); break; case MsgStartEncryptionRequest::TYPE: handleMsgStartEncryptionRequest(ss); break; case MsgAuthResponse::TYPE: handleMsgAuthResponse(ss); break; case MsgClientCsr::TYPE: handleMsgClientCsr(ss); break; case MsgSelectTG::TYPE: handleSelectTG(ss); break; case MsgTgMonitor::TYPE: handleTgMonitor(ss); break; case MsgNodeInfo::TYPE: handleNodeInfo(ss); break; case MsgSignalStrengthValues::TYPE: handleMsgSignalStrengthValues(ss); break; case MsgTxStatus::TYPE: handleMsgTxStatus(ss); break; #if 0 case MsgNodeInfo::TYPE: handleNodeInfo(ss); break; #endif case MsgRequestQsy::TYPE: handleRequestQsy(ss); break; case MsgStateEvent::TYPE: handleStateEvent(ss); break; case MsgError::TYPE: handleMsgError(ss); break; default: // Better just ignoring unknown protocol messages for making it easier to // add messages to the protocol and still be backwards compatible. //cerr << "*** WARNING: Unknown protocol message received: msg_type=" // << header.type() << endl; break; } } /* ReflectorClient::onFrameReceived */ void ReflectorClient::handleMsgProtoVer(std::istream& is) { if (m_con_state != STATE_EXPECT_PROTO_VER) { sendError("Protocol version expected"); return; } MsgProtoVer msg; if (!msg.unpack(is)) { geulog::error("client", "[", m_con->remoteHost(), ":", m_con->remotePort(), "]: Could not unpack MsgProtoVer"); sendError("Illegal MsgProtoVer protocol message received"); return; } m_client_proto_ver.set(msg.majorVer(), msg.minorVer()); ProtoVer max_proto_ver(MsgProtoVer::MAJOR, MsgProtoVer::MINOR); if (m_client_proto_ver > max_proto_ver) { if (m_con_state == STATE_EXPECT_PROTO_VER) { geulog::warn("client", m_con->remoteHost(), ":", m_con->remotePort(), ": Using protocol version ", msg.majorVer(), ".", msg.minorVer(), " which is newer than we can handle." " Asking for downgrade to ", MsgProtoVer::MAJOR, ".", MsgProtoVer::MINOR, "."); sendMsg(MsgProtoVerDowngrade()); } else { geulog::warn("client", m_con->remoteHost(), ":", m_con->remotePort(), ": Using protocol version ", msg.majorVer(), ".", msg.minorVer(), " which is newer than we can handle." " Downgrade failed."); std::ostringstream ss; ss << "Unsupported protocol version " << msg.majorVer() << "." << msg.minorVer() << ". May be at most " << MsgProtoVer::MAJOR << "." << MsgProtoVer::MINOR << "."; sendError(ss.str()); } return; } else if (m_client_proto_ver < ProtoVer(MIN_MAJOR_VER, MIN_MINOR_VER)) { geulog::error("client", "[", m_con->remoteHost(), ":", m_con->remotePort(), "]: Client is using protocol version ", msg.majorVer(), ".", msg.minorVer(), " which is too old. Must at least be version ", MIN_MAJOR_VER, ".", MIN_MINOR_VER, "."); std::ostringstream ss; ss << "Unsupported protocol version " << msg.majorVer() << "." << msg.minorVer() << ". Must be at least " << MIN_MAJOR_VER << "." << MIN_MINOR_VER << "."; sendError(ss.str()); return; } if (m_client_proto_ver.majorVer() >= 3) { //std::cout << "### ReflectorClient::handMsgProtoVer: Send CAInfo" // << std::endl; //m_con->setMaxRxFrameSize(ReflectorMsg::MAX_PRE_SSL_SETUP_FRAME_SIZE); sendMsg(MsgCAInfo(m_reflector->caSize(), m_reflector->caDigest())); m_con_state = STATE_EXPECT_START_ENCRYPTION; } else { sendAuthChallenge(); } } /* ReflectorClient::handleMsgProtoVer */ void ReflectorClient::handleMsgCABundleRequest(std::istream& is) { //std::cout << "### ReflectorClient::handleMsgCABundleRequest" << std::endl; if (m_con_state != STATE_EXPECT_START_ENCRYPTION) { geulog::error("client", "[", m_con->remoteHost(), ":", m_con->remotePort(), "] Unexpected MsgCABundleRequest"); disconnect(); return; } //std::cout << "### Sending CA Bundle" << std::endl; //m_con->setMaxRxFrameSize(ReflectorMsg::MAX_PRE_SSL_SETUP_FRAME_SIZE); sendMsg(MsgCABundle(m_reflector->caBundlePem(), m_reflector->caSignature(), m_reflector->issuingCertPem())); } /* ReflectorClient::handleMsgCABundleRequest */ void ReflectorClient::handleMsgStartEncryptionRequest(std::istream& is) { //std::cout << "### ReflectorClient::handleMsgStartEncryptionRequest" // << std::endl; if (m_con_state != STATE_EXPECT_START_ENCRYPTION) { geulog::error("client", "[", m_con->remoteHost(), ":", m_con->remotePort(), "] Unexpected MsgStartEncryptionRequest"); disconnect(); return; } MsgStartEncryptionRequest msg; if (!msg.unpack(is)) { geulog::error("client", "[", m_con->remoteHost(), ":", m_con->remotePort(), "] Could not unpack MsgStartEncryptionRequest"); disconnect(); return; } geulog::info("client", m_con->remoteHost(), ":", m_con->remotePort(), ": Starting encryption"); m_con->setMaxRxFrameSize(ReflectorMsg::MAX_SSL_SETUP_FRAME_SIZE); sendMsg(MsgStartEncryption()); m_con->enableSsl(true); m_con_state = STATE_EXPECT_SSL_CON_READY; } /* ReflectorClient::handleMsgStartEncryptionRequest */ void ReflectorClient::handleMsgAuthResponse(std::istream& is) { if (m_con_state != STATE_EXPECT_AUTH_RESPONSE) { geulog::error("client", "[", m_con->remoteHost(), ":", m_con->remotePort(), "] Authentication response unexpected"); sendError("Authentication response unexpected"); return; } MsgAuthResponse msg; if (!msg.unpack(is)) { geulog::error("client", "[", m_con->remoteHost(), ":", m_con->remotePort(), "] Could not unpack MsgAuthResponse"); sendError("Illegal MsgAuthResponse protocol message received"); return; } if (!m_reflector->callsignOk(msg.callsign())) { geulog::error("client", "[", m_con->remoteHost(), ":", m_con->remotePort(), "] Invalid node callsign '", msg.callsign(), "' in MsgAuthResponse"); sendError("Invalid callsign"); return; } //const auto peer_cert = m_reflector->loadClientCertificate(msg.callsign()); //if (!peer_cert.isNull()) //{ // std::cout << "Client " << m_con->remoteHost() << ":" // << m_con->remotePort() << " (" << msg.callsign() << "?)" // << ": Sending client certificate to peer" << std::endl; // //sendMsg(MsgClientCert(peer_cert.pem())); // sendClientCert(peer_cert); // //m_con_state = STATE_EXPECT_CSR; // return; //} //else //if (m_reflector->loadClientPendingCsr(msg.callsign()).isNull()) //{ // std::cout << "Client " << m_con->remoteHost() << ":" // << m_con->remotePort() << " (" << msg.callsign() << "?)" // << ": Sending CSR request to peer" << std::endl; // sendMsg(MsgClientCsrRequest()); //} string auth_key = lookupUserKey(msg.callsign()); if (!auth_key.empty() && msg.verify(auth_key, m_auth_challenge)) { geulog::info("client", msg.callsign(), ": Received valid auth key"); connectionAuthenticated(msg.callsign()); } else { geulog::error("client", "[", m_con->remoteHost(), ":", m_con->remotePort(), "] Authentication failed for user '", msg.callsign(), "'"); sendError("Access denied"); } } /* ReflectorClient::handleMsgAuthResponse */ void ReflectorClient::handleMsgClientCsr(std::istream& is) { std::ostringstream idss; if (m_con_state == STATE_CONNECTED) { idss << m_callsign; } else { idss << m_con->remoteHost() << ":" << m_con->remotePort(); } if ((m_con_state != STATE_CONNECTED) && (m_con_state != STATE_EXPECT_CSR)) { geulog::error("client", "[", idss.str(), "] Certificate Signing Request unexpected"); sendError("Certificate Signing Request unexpected"); return; } MsgClientCsr msg; if (!msg.unpack(is)) { geulog::error("client", "[", idss.str(), "] Could not unpack MsgClientCsr"); sendError("Illegal MsgClientCsr protocol message received"); return; } geulog::info("client", idss.str(), ": Received CSR"); Async::SslCertSigningReq req; if (!req.readPem(msg.csrPem()) || req.isNull()) { geulog::error("client", "[", idss.str(), "] Invalid CSR received:\n", msg.csrPem()); sendError("Invalid CSR received"); return; } req.print(idss.str() + ": "); auto errstr = m_reflector->checkCsr(req); if (!errstr.empty()) { geulog::error("client", "[", idss.str(), "] ", errstr); sendError(errstr); return; } auto cert = m_reflector->csrReceived(req); auto current_req = m_reflector->loadClientCsr(req.commonName()); if (( (m_con_state == STATE_EXPECT_CSR) || (!current_req.isNull() && (req.digest() == current_req.digest())) ) && sendClientCert(cert)) { geulog::info("client", idss.str(), ": Sent certificate to peer"); //cert.print(); m_con_state = STATE_EXPECT_DISCONNECT; } else if (m_con_state == STATE_EXPECT_CSR) { geulog::info("client", idss.str(), ": No valid certificate found matching CSR. " "Sending authentication challenge."); sendAuthChallenge(); m_con_state = STATE_EXPECT_AUTH_RESPONSE; } } /* ReflectorClient::handleMsgClientCsr */ void ReflectorClient::handleSelectTG(std::istream& is) { MsgSelectTG msg; if (!msg.unpack(is)) { geulog::error("client", "Client ", m_con->remoteHost(), ":", m_con->remotePort(), ": Could not unpack MsgSelectTG"); sendError("Illegal MsgSelectTG protocol message received"); return; } uint32_t sel_tg = msg.tg(); if (m_reflector != nullptr) { uint32_t folded = m_reflector->aliasSelect(sel_tg); if (folded != sel_tg) { geulog::info("client", m_callsign, ": alias-fold select TG #", sel_tg, " -> #", folded); sel_tg = folded; } } if (sel_tg != m_current_tg) { auto talker = TGHandler::instance()->talkerForTG(m_current_tg); if (talker == this) { m_reflector->broadcastUdpMsg(MsgUdpFlushSamples(), mkAndFilter( TgFilter(m_current_tg), ExceptFilter(this))); } else if (talker != 0) { sendUdpMsg(MsgUdpFlushSamples()); } setTg(sel_tg); } } /* ReflectorClient::handleSelectTG */ void ReflectorClient::handleTgMonitor(std::istream& is) { MsgTgMonitor msg; if (!msg.unpack(is)) { geulog::error("client", "Client ", m_con->remoteHost(), ":", m_con->remotePort(), ": Could not unpack MsgTgMonitor"); sendError("Illegal MsgTgMonitor protocol message received"); return; } std::set tgs; for (const auto& tg : msg.tgs()) { uint32_t mon_tg = tg; if (m_reflector != nullptr) { mon_tg = m_reflector->aliasSelect(mon_tg); if (mon_tg != tg) { geulog::info("client", m_callsign, ": alias-fold monitor TG #", tg, " -> #", mon_tg); } } if (!TGHandler::instance()->allowTgMonitoring(this, mon_tg) || (mon_tg == 0)) { geulog::info("client", m_callsign, ": Not allowed to monitor TG #", mon_tg); continue; } tgs.insert(mon_tg); } { std::ostringstream tglist; std::copy(tgs.begin(), tgs.end(), std::ostream_iterator(tglist, " ")); geulog::info("client", m_callsign, ": Monitor TG#: [ ", tglist.str(), "]"); } setMonitoredTGs(tgs); } /* ReflectorClient::handleTgMonitor */ void ReflectorClient::handleNodeInfo(std::istream& is) { std::string jsonstr; if (m_client_proto_ver >= ProtoVer(3, 0)) { MsgNodeInfo msg; if (!msg.unpack(is)) { geulog::error("client", "Client ", m_con->remoteHost(), ":", m_con->remotePort(), ": Could not unpack MsgNodeInfo"); sendError("Illegal MsgNodeInfo protocol message received"); return; } //std::cout << "### handleNodeInfo: udpSrcPort()=" << msg.udpSrcPort() // << " JSON=" << msg.json() << std::endl; //setRemoteUdpSource(msg.udpSrcPort()); setUdpCipherIVRand(msg.ivRand()); setUdpCipherKey(msg.udpCipherKey()); jsonstr = msg.json(); sendMsg(MsgStartUdpEncryption()); } else { MsgNodeInfoV2 msg; if (!msg.unpack(is)) { geulog::error("client", "Client ", m_con->remoteHost(), ":", m_con->remotePort(), ": Could not unpack MsgNodeInfoV2"); sendError("Illegal MsgNodeInfo protocol message received"); return; } jsonstr = msg.json(); } try { m_status = &(m_reflector->clientStatus(m_callsign)); auto& status = *m_status; status.clear(); std::istringstream is(jsonstr); is >> status; status["protoVer"]["majorVer"] = protoVer().majorVer(); status["protoVer"]["minorVer"] = protoVer().minorVer(); setMonitoredTGs(m_monitored_tgs); setTg(m_current_tg); if (status.isMember("qth") && status["qth"].isArray()) { //std::cout << "### Found qth" << std::endl; Json::Value& qths(status["qth"]); for (Json::Value::ArrayIndex i=0; ipublishClientStatus(this); } /* ReflectorClient::handleNodeInfo */ void ReflectorClient::handleMsgSignalStrengthValues(std::istream& is) { MsgSignalStrengthValues msg; if (!msg.unpack(is)) { geulog::warn("client", "[", callsign(), "]: Could not unpack incoming MsgSignalStrengthValues message"); return; } typedef MsgSignalStrengthValues::Rxs::const_iterator RxsIter; for (RxsIter it = msg.rxs().begin(); it != msg.rxs().end(); ++it) { const MsgSignalStrengthValues::Rx& rx = *it; //std::cout << "### MsgSignalStrengthValues:" // << " id=" << rx.id() // << " siglev=" << rx.siglev() // << " enabled=" << rx.enabled() // << " sql_open=" << rx.sqlOpen() // << " active=" << rx.active() // << std::endl; setRxSiglev(rx.id(), rx.siglev()); setRxEnabled(rx.id(), rx.enabled()); setRxSqlOpen(rx.id(), rx.sqlOpen()); setRxActive(rx.id(), rx.active()); } m_reflector->publishRxUpdate(this); } /* ReflectorClient::handleMsgSignalStrengthValues */ void ReflectorClient::handleMsgTxStatus(std::istream& is) { MsgTxStatus msg; if (!msg.unpack(is)) { geulog::warn("client", "[", callsign(), "]: Could not unpack incoming MsgTxStatus message"); return; } typedef MsgTxStatus::Txs::const_iterator TxsIter; for (TxsIter it = msg.txs().begin(); it != msg.txs().end(); ++it) { const MsgTxStatus::Tx& tx = *it; //std::cout << "### MsgTxStatus:" // << " id=" << tx.id() // << " transmit=" << tx.transmit() // << std::endl; setTxTransmit(tx.id(), tx.transmit()); } } /* ReflectorClient::handleMsgTxStatus */ void ReflectorClient::handleRequestQsy(std::istream& is) { MsgRequestQsy msg; if (!msg.unpack(is)) { geulog::error("client", "Client ", m_con->remoteHost(), ":", m_con->remotePort(), ": Could not unpack MsgRequestQsy"); sendError("Illegal MsgRequestQsy protocol message received"); return; } m_reflector->requestQsy(this, msg.tg()); } /* ReflectorClient::handleRequestQsy */ void ReflectorClient::handleStateEvent(std::istream& is) { MsgStateEvent msg; if (!msg.unpack(is)) { geulog::error("client", "Client ", m_con->remoteHost(), ":", m_con->remotePort(), ": Could not unpack MsgStateEvent"); sendError("Illegal MsgStateEvent protocol message received"); return; } geulog::debug("client", "StateEvent: src=", msg.src(), " name=", msg.name(), " msg=", msg.msg()); } /* ReflectorClient::handleStateEvent */ #if 0 void ReflectorClient::handleNodeInfo(std::istream& is) { MsgNodeInfo msg; if (!msg.unpack(is)) { cout << "Client " << m_con->remoteHost() << ":" << m_con->remotePort() << " ERROR: Could not unpack MsgNodeInfo" << endl; sendError("Illegal MsgNodeInfo protocol message received"); return; } cout << m_callsign << ": Client info" << "\n--- Software: \"" << msg.swInfo() << "\""; for (size_t i=0; i(cout, " ")); } } for (size_t i=0; i(cout, " ")); } if (tx_site.txPowerIsValid()) { cout << "\n--- TX Power : " << tx_site.txPower() << "W"; } } //if (!msg.qthName().empty()) //{ // cout << "\n--- QTH Name=\"" << msg.qthName() << "\""; //} cout << endl; } /* ReflectorClient::handleNodeInfo */ #endif void ReflectorClient::handleMsgError(std::istream& is) { MsgError msg; string message; if (msg.unpack(is)) { message = msg.message(); } { const std::string id = m_callsign.empty() ? (m_con->remoteHost().toString() + ":" + std::to_string(m_con->remotePort())) : m_callsign; geulog::info("client", id, ": Error message received from client: ", message); } disconnect(); } /* ReflectorClient::handleMsgError */ void ReflectorClient::sendError(const std::string& msg) { sendMsg(MsgError(msg)); m_heartbeat_timer.setEnable(false); m_remote_udp_port = 0; m_disc_timer.setEnable(true); m_con_state = STATE_EXPECT_DISCONNECT; } /* ReflectorClient::sendError */ void ReflectorClient::onDiscTimeout(Timer *t) { assert(m_con_state == STATE_EXPECT_DISCONNECT); disconnect(); } /* ReflectorClient::onDiscTimeout */ void ReflectorClient::disconnect(void) { m_heartbeat_timer.setEnable(false); m_remote_udp_port = 0; m_con->disconnect(); m_con_state = STATE_DISCONNECTED; m_con->disconnected(m_con, FramedTcpConnection::DR_ORDERED_DISCONNECT); } /* ReflectorClient::disconnect */ void ReflectorClient::handleHeartbeat(Async::Timer *t) { if (--m_heartbeat_tx_cnt == 0) { sendMsg(MsgHeartbeat()); } if (--m_udp_heartbeat_tx_cnt == 0) { sendUdpMsg(MsgUdpHeartbeat()); } if (--m_heartbeat_rx_cnt == 0) { const std::string id = callsign().empty() ? ("Client " + m_con->remoteHost().toString() + ":" + std::to_string(m_con->remotePort())) : callsign(); geulog::info("client", id, ": TCP heartbeat timeout"); sendError("TCP heartbeat timeout"); } if (--m_udp_heartbeat_rx_cnt == 0) { const std::string id = callsign().empty() ? ("Client " + m_con->remoteHost().toString() + ":" + std::to_string(m_con->remotePort())) : callsign(); geulog::info("client", id, ": UDP heartbeat timeout"); sendError("UDP heartbeat timeout"); } if (m_blocktime > 0) { if (m_remaining_blocktime == 0) { setBlock(0); } else { m_remaining_blocktime -= 1; } } } /* ReflectorClient::handleHeartbeat */ std::string ReflectorClient::lookupUserKey(const std::string& callsign) { if (m_reflector->redisStore() != nullptr) { std::string key = m_reflector->redisStore()->lookupUserKey(callsign); if (key.empty()) { geulog::warn("client", "Redis lookup failed for user \"", callsign, "\""); } return key; } string auth_group; if (!m_cfg->getValue("USERS", callsign, auth_group) || auth_group.empty()) { geulog::warn("client", "Unknown user \"", callsign, "\""); return ""; } string auth_key; if (!m_cfg->getValue("PASSWORDS", auth_group, auth_key) || auth_key.empty()) { geulog::error("client", "User \"", callsign, "\" found in SvxReflector " "configuration but password with groupname \"", auth_group, "\" not found."); return ""; } return auth_key; } /* ReflectorClient::lookupUserKey */ void ReflectorClient::connectionAuthenticated(const std::string& callsign) { vector connected_nodes; m_reflector->nodeList(connected_nodes); if (find(connected_nodes.begin(), connected_nodes.end(), callsign) == connected_nodes.end()) { m_con->setMaxRxFrameSize(ReflectorMsg::MAX_POSTAUTH_FRAME_SIZE); m_callsign = callsign; sendMsg(MsgAuthOk()); geulog::info("client", m_callsign, ": Login OK from ", m_con->remoteHost(), ":", m_con->remotePort(), " with protocol version ", m_client_proto_ver.majorVer(), ".", m_client_proto_ver.minorVer()); m_con_state = STATE_CONNECTED; assert(client_callsign_map.find(m_callsign) == client_callsign_map.end()); client_callsign_map[m_callsign] = this; MsgServerInfo msg_srv_info(m_client_id, m_supported_codecs); m_reflector->nodeList(msg_srv_info.nodes()); sendMsg(msg_srv_info); if (m_client_proto_ver < ProtoVer(0, 7)) { MsgNodeList msg_node_list(msg_srv_info.nodes()); sendMsg(msg_node_list); } if (m_client_proto_ver < ProtoVer(2, 0)) { setTg(m_reflector->tgForV1Clients()); } m_reflector->broadcastMsg(MsgNodeJoined(m_callsign), ExceptFilter(this)); m_reflector->onClientAuthenticated(m_callsign, currentTG(), m_con->remoteHost().toString()); } else { geulog::info("client", callsign, ": Already connected"); sendError("Access denied"); } } /* ReflectorClient::connectionAuthenticated */ bool ReflectorClient::sendClientCert(const Async::SslX509& cert) { if (cert.isNull()) { return false; } const auto callsign = cert.commonName(); const auto pending_csr = m_reflector->loadClientPendingCsr(callsign); if (!pending_csr.isNull() && (cert.publicKey() != pending_csr.publicKey())) { //std::cout << "### ReflectorClient::sendClientCert: Cert public key " // "differs compared to pending CSR public key" << std::endl; //sendMsg(MsgClientCert()); return false; } return sendMsg(MsgClientCert(m_reflector->clientCertPem(callsign))); } /* ReflectorClient::sendClientCert */ void ReflectorClient::sendAuthChallenge(void) { MsgAuthChallenge challenge_msg; if (challenge_msg.challenge() == nullptr) { disconnect(); return; } memcpy(m_auth_challenge, challenge_msg.challenge(), MsgAuthChallenge::LENGTH); sendMsg(challenge_msg); m_con_state = STATE_EXPECT_AUTH_RESPONSE; } /* ReflectorClient::sendAuthChallenge */ void ReflectorClient::renewClientCertificate(void) { auto cert = m_con->sslPeerCertificate(); if (cert.isNull() || !m_reflector->renewedClientCert(cert)) { geulog::warn("client", "Certificate renewal for '", m_callsign, "' failed"); return; } geulog::info("client", m_callsign, ": Send renewed client certificate"); sendClientCert(cert); m_con_state = STATE_EXPECT_DISCONNECT; } /* ReflectorClient::renewClientCertificate */ void ReflectorClient::setMonitoredTGs(const std::set& tgs) { m_monitored_tgs = tgs; if (m_status != nullptr) { if (!m_status->isMember("monitoredTGs") || !(*m_status)["monitoredTGs"].isArray()) { (*m_status)["monitoredTGs"] = Json::Value(Json::arrayValue); } Json::Value& monitored_tgs = (*m_status)["monitoredTGs"]; monitored_tgs.clear(); for (const auto& tg : tgs) { monitored_tgs.append(tg); } } if (m_reflector != nullptr) { m_reflector->publishClientStatus(this); // Monitored set drives MsgPeerTgInterest; tell trunk peers so they can // forward audio without waiting for a PTT to bootstrap interest. m_reflector->scheduleTgInterestUpdate(); } } /* ReflectorClient::setMonitoredTGs */ void ReflectorClient::setTg(uint32_t tg) { if (tg != m_current_tg) { if (TGHandler::instance()->switchTo(this, tg)) { geulog::info("client", m_callsign, ": Select TG #", tg); } else { // FIXME: Notify the client that the TG selection was not allowed geulog::info("client", m_callsign, ": Not allowed to use TG #", tg); TGHandler::instance()->switchTo(this, 0); tg = 0; } m_current_tg = tg; if (m_reflector != nullptr) { m_reflector->scheduleNodeListUpdate(); m_reflector->scheduleTgInterestUpdate(); } } if (m_status != nullptr) { if (!TGHandler::instance()->showActivity(tg)) { tg = 0; } (*m_status)["tg"] = tg; (*m_status)["restrictedTG"] = TGHandler::instance()->isRestricted(tg); } updateIsTalker(); if (m_reflector != nullptr) m_reflector->publishClientStatus(this); } /* ReflectorClient::setTg */ /* * This file has not been truncated */