// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL #include "MatrixRoomBridge.h" #include "MatrixRoomBridge_p.h" #include "koutnet_matrix_debug.h" #include "network/NetworkManager.h" #include "network/VoiceCallManager.h" #include #include #include #include using namespace Quotient; namespace koutnet { // KOutNet - Matrix calls: the stack the bridge is handed, an SDP blob turned into // an offer, and the four moves of a call (ring, accept, decline, hang up). void MatrixRoomBridge::setCallStack(NetworkManager *net, VoiceCallManager *voice) { m_net = net; m_voice = voice; } MatrixRoomBridge::CallOffer MatrixRoomBridge::ownCallOffer() const { CallOffer offer; // the address the LAN path already announces. the host candidate carries // the listener port this side actually bound, so a remote dial reaches the // voice server even when the well-known port was taken. the key is fresh // per call, so no two room calls share a keystream even on the same pair // of ends. if (m_net != nullptr) { offer.address = m_net->hostIp(); const QString hostCandidate = QStringLiteral("%1:%2").arg(offer.address).arg(m_net->tcpPort()); offer.candidates.append(hostCandidate); // the reflexive address is where the outside sees this station; both // sides dialing their peer's reflexive address is how two dials cross // a NAT pair as one connection. missing entirely while no STUN server // was reachable, and that happens without breaking LAN/VPN calls. const QString reflex = m_net->stunReflexive(); if (!reflex.isEmpty() && matrix::saneCallAddress(reflex) && !offer.candidates.contains(reflex)) offer.candidates.append(reflex); } return offer; } MatrixRoomBridge::CallOffer MatrixRoomBridge::callOfferFromSdp(const QString &sdp) { CallOffer offer; const QStringList parts = sdp.split(QLatin1Char(' '), Qt::SkipEmptyParts); if (parts.size() < 2 || parts.at(0) != QLatin1String("koutnet")) return offer; offer.address = parts.at(1); // the offer is a stranger's room event, not this side's own handshake: a // bare address that fails the unicast check is dropped before it can be // shown, queued or dialed. An attacker gets no feedback but a log line. if (!matrix::saneCallAddress(offer.address)) { qCWarning(KOUTNET_LOG_MATRIX) << "ignoring a room call offer with an unusable media address"; return {}; } // A candidate list ("c=host,stun") names every address to dial in parallel. // The primary address is always one of them; any extra candidate is // validated alone, so one malformed token cannot smuggle a dial target past // the filter. A bound keeps one offer from widening into an unbounded dial. for (const QString &token : parts) { if (!token.startsWith(QLatin1String("c="))) continue; const QStringList raw = token.mid(2).split(QLatin1Char(','), Qt::SkipEmptyParts); for (const QString &candidate : raw) { if (matrix::saneCallAddress(candidate) && !offer.candidates.contains(candidate)) offer.candidates.append(candidate); } } if (!offer.candidates.contains(offer.address)) offer.candidates.prepend(offer.address); while (offer.candidates.size() > 5) offer.candidates.removeLast(); return offer; } void MatrixRoomBridge::callRoom(const QString &chatId) { Room *room = roomFor(chatId); const CallOffer offer = ownCallOffer(); if (room == nullptr || offer.address.isEmpty() || m_calls.contains(chatId)) return; if (!roomCallAllowed(room)) { Q_EMIT sendFailed(chatId, i18nc("@info:status", "Room calls need an end-to-end encrypted room - the media address would leak otherwise.")); return; } RoomCall call; call.callId = QUuid::createUuid().toString(QUuid::WithoutBraces); call.role = QStringLiteral("caller"); m_calls.insert(chatId, call); // the legacy "lifetime" field of m.call.invite. the server expects the event // to look like a call even though nothing about it goes through the server. // the offer carries this side's media address and the candidates to dial it // by; the media itself is sealed by the TLS voice channel, so nothing else // has to travel with the call. QStringList tokens{QStringLiteral("koutnet"), offer.address}; if (!offer.candidates.isEmpty()) tokens << QStringLiteral("c=%1").arg(offer.candidates.join(QLatin1Char(','))); const QString sdp = tokens.join(QLatin1Char(' ')); room->postJson(QStringLiteral("m.call.invite"), QJsonObject{{QStringLiteral("call_id"), call.callId}, {QStringLiteral("version"), 0}, {QStringLiteral("party_id"), room->connection() ? room->connection()->userId() : QString()}, {QStringLiteral("lifetime"), 120000}, {QStringLiteral("offer"), QJsonObject{{QStringLiteral("type"), QStringLiteral("offer")}, {QStringLiteral("sdp"), sdp}}}}); } void MatrixRoomBridge::queueCallOffer(const QString &chatId, const QString &callId, Quotient::Room *room, const QString &senderName, const CallOffer &offer) { Q_UNUSED(room); // one pending invite at a time, matching the single dialog. A second offer // that races the one on screen is dropped rather than silently replacing // the address the user is about to judge - a flood of invitations cannot // thrash the window into showing an ever-newer target. if (!m_pending.chatId.isEmpty()) { qCInfo(KOUTNET_LOG_MATRIX) << "ignoring a room call offer while another invite is pending, chat" << chatId; return; } // the dialog discloses every address accepting will dial, not just the // first: a peer that offers a private candidate is letting the user see it // before consent covers it. const QString dialTargets = offer.candidates.isEmpty() ? offer.address : offer.candidates.join(QStringLiteral(", ")); m_pending = PendingCall{chatId, callId, offer.address, offer.candidates}; Q_EMIT roomCallInvited(chatId, callId, senderName, dialTargets); } void MatrixRoomBridge::acceptCall(const QString &chatId, const QString &callId) { Room *room = roomFor(chatId); if (room == nullptr || m_pending.chatId != chatId || m_pending.callId != callId) return; // answering a call posts this side's media address. like the media the // address dials to, it is sealed by the TLS voice channel, not by the room; // the e2ee-room gate keeps even the address and candidates from reading by // anyone but the peer. if (!roomCallAllowed(room)) { m_pending = PendingCall(); Q_EMIT sendFailed(chatId, i18nc("@info:status", "Room calls need an end-to-end encrypted room - the media address would leak otherwise.")); return; } const CallOffer offer = ownCallOffer(); if (offer.address.isEmpty()) return; // the consent the confirmation dialog granted covers exactly this: dial the // peer address the offer named. no other code path opens a room-call media // channel. const QString peerAddress = m_pending.peerAddress; auto it = m_calls.find(chatId); if (it == m_calls.end()) { // first answer: the pair dials each other through their candidates. RoomCall call; call.callId = callId; call.role = QStringLiteral("answerer"); call.peerAddresses.append(peerAddress); call.established = true; m_calls.insert(chatId, call); const QString sdpMedia = QStringLiteral("koutnet %1").arg(offer.address); // the answer carries the answerer's candidates too, because the caller // dials them back - that simultaneous open is what punches a NAT pair. QStringList answerTokens{sdpMedia}; if (!offer.candidates.isEmpty()) answerTokens << QStringLiteral("c=%1").arg(offer.candidates.join(QLatin1Char(','))); const QString sdp = answerTokens.join(QLatin1Char(' ')); room->postJson(QStringLiteral("m.call.answer"), QJsonObject{{QStringLiteral("call_id"), callId}, {QStringLiteral("party_id"), room->connection() ? room->connection()->userId() : QString()}, {QStringLiteral("answer"), QJsonObject{{QStringLiteral("type"), QStringLiteral("answer")}, {QStringLiteral("sdp"), sdp}}}}); } else { // A further member joining a call this side is already in, found through // the same confirmation dialog as the first invite. if (it->callId != callId || it->peerAddresses.contains(peerAddress)) { m_pending = PendingCall(); return; } it->peerAddresses.append(peerAddress); } if (m_voice != nullptr) m_voice->call(peerAddress, m_pending.peerCandidates); m_pending = PendingCall(); Q_EMIT roomCallAccepted(chatId); } void MatrixRoomBridge::declineCall(const QString &chatId, const QString &callId) { Room *room = roomFor(chatId); if (room == nullptr || m_pending.chatId != chatId || m_pending.callId != callId) return; // A first invite answers politely with a hangup. An invite that only offered // to add a peer to a call already on screen gets no response at all: a // hangup under its call id would tear down the whole room call. if (!m_calls.contains(chatId)) { room->postJson(QStringLiteral("m.call.hangup"), QJsonObject{{QStringLiteral("call_id"), callId}, {QStringLiteral("party_id"), room->connection() ? room->connection()->userId() : QString()}, {QStringLiteral("reason"), QStringLiteral("decline")}}); } m_pending = PendingCall(); } void MatrixRoomBridge::hangupRoomCall(const QString &chatId) { Room *room = roomFor(chatId); const auto it = m_calls.find(chatId); if (it == m_calls.end()) return; if (room != nullptr) { room->postJson(QStringLiteral("m.call.hangup"), QJsonObject{{QStringLiteral("call_id"), it->callId}, {QStringLiteral("party_id"), room->connection() ? room->connection()->userId() : QString()}, {QStringLiteral("reason"), QStringLiteral("hangup")}}); } const auto addresses = it->peerAddresses; for (const QString &address : addresses) { if (m_voice != nullptr) m_voice->hangup(address); } m_calls.erase(it); if (m_pending.chatId == chatId) m_pending = PendingCall(); Q_EMIT roomCallEnded(chatId); } void MatrixRoomBridge::handleCallEvent(Room *room, const RoomEvent *event) { if (room == nullptr || event == nullptr) return; const QString chatId = chatid::matrixChatId(room->id()); const QString ownId = room->connection() ? room->connection()->userId() : QString(); if (event->senderId() == ownId) return; const auto it = m_calls.find(chatId); if (const auto *invite = eventCast(event)) { const CallOffer offer = callOfferFromSdp(invite->sdp()); // Anything the address validator rejected is dropped before it can be // queued or shown, so a malformed offer cannot even knock the pending // slot out from under a legitimate one. if (offer.address.isEmpty()) return; const QString senderName = room->member(event->senderId()).displayName(); if (it != m_calls.end() && it->callId == invite->callId()) { // A member re-inviting a call this side is already in: a group-call // member joining. Never connecting on its own - the join waits for // the same confirmation as the first invite. if (!it->peerAddresses.contains(offer.address)) queueCallOffer(chatId, invite->callId(), room, senderName, offer); return; } // A call this session has never seen: offer it to the window. Only one // pending invite is carried, matching the single dialog. queueCallOffer(chatId, invite->callId(), room, senderName, offer); return; } if (const auto *answer = eventCast(event)) { if (it == m_calls.end() || it->callId != answer->callId()) return; const CallOffer offer = callOfferFromSdp(answer->sdp()); if (offer.address.isEmpty()) return; // The member who answered this side's own offer takes on the media here: // dialing the answerer's candidates back opens the TLS voice channel. // Dialing each other's sets at the same time is what turns two outbound // dials through a NAT pair into one connection. if (it->role == QLatin1String("caller") && it->peerAddresses.isEmpty()) { it->peerAddresses.append(offer.address); it->established = true; if (m_voice != nullptr) m_voice->call(offer.address, offer.candidates); return; } // Any further answer is a member joining a call that is already up: // connecting is gated on the same confirmation as the first invite. if (!it->peerAddresses.contains(offer.address)) queueCallOffer(chatId, answer->callId(), room, room->member(event->senderId()).displayName(), offer); return; } if (const auto *hangup = eventCast(event)) { (void)hangup; const auto it = m_calls.find(chatId); if (it != m_calls.end()) { const auto addresses = it->peerAddresses; for (const QString &address : addresses) { if (m_voice != nullptr) m_voice->hangup(address); } m_calls.erase(it); Q_EMIT roomCallEnded(chatId); } if (m_pending.chatId == chatId) m_pending = PendingCall(); } } } // namespace koutnet