// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL // KOutNet - Reassembles chunked file transfers received over the session transport #include "FileTransferHandler.h" #include #include #include #include #include #include #include #include #include #include namespace koutnet { FileTransferHandler::FileTransferHandler(QObject *parent) : QObject(parent) { connect(&m_pruneTimer, &QTimer::timeout, this, &FileTransferHandler::pruneStaleTransfers); m_pruneTimer.start(60'000); // sweep once a minute } void FileTransferHandler::setMaxTransferBytes(qint64 bytes) { m_maxTransferBytes = bytes; } QString FileTransferHandler::sanitizeFilename(const QString &rawName) { const QString fallback = QStringLiteral("file_%1").arg(QDateTime::currentMSecsSinceEpoch()); // Cut at the last separator of either kind: QFileInfo::fileName() only knows the // forward slash on Unix, so a backslash path survives it whole. QString name = rawName; const qsizetype cut = qMax(name.lastIndexOf(QLatin1Char('/')), name.lastIndexOf(QLatin1Char('\\'))); if (cut >= 0) name = name.mid(cut + 1); // NULs and control characters go first: QFile hands the path to the C API, which // stops at the first NUL, so the path checked is not the path opened. QString clean; clean.reserve(name.size()); for (const QChar c : std::as_const(name)) { if (c.unicode() >= 0x20 && c.unicode() != 0x7F) clean.append(c); } name = clean; if (name.isEmpty() || name.count(QLatin1Char('.')) == name.size()) return fallback; while (name.toUtf8().size() > kMaxFilenameBytes && !name.isEmpty()) name.chop(1); if (name.isEmpty() || name.count(QLatin1Char('.')) == name.size()) return fallback; return name; } qint64 FileTransferHandler::pendingBufferedBytes() const { qint64 total = 0; for (auto it = m_pending.constBegin(); it != m_pending.constEnd(); ++it) total += it.value().receivedBytes; return total; } void FileTransferHandler::onMetaOffered(const QString &host, const QJsonObject &meta) { const QString tid = meta.value(QStringLiteral("tid")).toString(); if (tid.isEmpty()) return; // An id already in flight cannot be offered again. if (m_pending.contains(tid)) { Q_EMIT transferRejected(tid, i18nc("@info:status file transfer refused", "A transfer with this id is already in progress.")); return; } // The first peer to announce an id keeps it, same as the reassembler does with // the chunks. Otherwise a second peer could repeat the meta before the user // answered and quietly take the transfer over. const auto known = m_offers.constFind(tid); if (known != m_offers.constEnd() && known->host != host) { Q_EMIT transferRejected(tid, i18nc("@info:status file transfer refused", "Another peer already announced this transfer.")); return; } // Offers cost one meta object each and nothing consumes them until the user // answers, so the table is capped the same way the transfer table is. if (known == m_offers.constEnd() && m_offers.size() >= kMaxPendingTransfers) { Q_EMIT transferRejected(tid, i18nc("@info:status file transfer refused", "Too many transfers are waiting to be accepted.")); return; } Offer &offer = m_offers[tid]; offer.meta = meta; offer.host = host; offer.offeredAtMs = QDateTime::currentMSecsSinceEpoch(); } void FileTransferHandler::acceptOffer(const QString &tid) { const auto it = m_offers.constFind(tid); if (it == m_offers.constEnd()) return; // the size is checked here rather than on the frame: the cap can be lowered // between the offer and the answer, and this is the last point before bytes // start being buffered const QJsonValue sizeValue = it->meta.value(QStringLiteral("size")); const double announced = sizeValue.toDouble(-1.0); if (!sizeValue.isDouble() || !qIsFinite(announced) || announced < 0.0 || std::trunc(announced) != announced || announced > double(std::numeric_limits::max()) || announced > double(m_maxTransferBytes)) { m_offers.remove(tid); Q_EMIT transferRejected(tid, i18nc("@info:status file transfer refused", "The announced size is not a usable length.")); return; // no entry created - onChunkMessage will drop its chunks } if (m_pending.size() >= kMaxPendingTransfers) { m_offers.remove(tid); Q_EMIT transferRejected(tid, i18nc("@info:status file transfer refused", "Too many concurrent incoming transfers.")); return; } PendingTransfer &t = m_pending[tid]; t.meta = it->meta; t.total = -1; // filled in once, by the first chunk's "total" field t.announcedBytes = qint64(announced); t.chunks.clear(); t.receivedBytes = 0; t.startedAtMs = QDateTime::currentMSecsSinceEpoch(); t.sender = it->host; m_offers.remove(tid); } void FileTransferHandler::declineOffer(const QString &tid) { m_offers.remove(tid); } void FileTransferHandler::onChunkMessage(const QString &host, const QString &tid, int idx, int total, const QByteArray &chunk) { if (tid.isEmpty() || !m_pending.contains(tid)) return; // chunk for a transfer we never saw (or rejected) meta for - drop it PendingTransfer &t = m_pending[tid]; // A pinned peer that knows somebody else's tid is still not its sender, so // it gets to add neither a chunk nor a second set of bytes under an index // it already used. if (t.sender != host) return; if (idx < 0 || total <= 0 || idx >= total) return; // Reject a transfer that grows past the cap whatever the attacker-controlled // meta claimed: meta.size=small with far more or larger chunks than announced. const qint64 maxChunks = (m_maxTransferBytes / 1024) + 1024; // generous upper bound if (total > maxChunks) { m_pending.remove(tid); Q_EMIT transferRejected(tid, i18nc("@info:status file transfer refused", "The chunk count exceeds the limit.")); return; } if (t.total >= 0 && t.total != total) { m_pending.remove(tid); Q_EMIT transferRejected(tid, i18nc("@info:status file transfer refused", "The chunk count changed during the transfer.")); return; } t.total = total; const auto held = t.chunks.constFind(idx); if (held != t.chunks.constEnd() && *held != chunk) { // a peer resending an index with different bytes is either broken or // walking the whole range twice to hide the second pass from the cap m_pending.remove(tid); Q_EMIT transferRejected(tid, i18nc("@info:status file transfer refused", "A chunk was resent with different contents.")); return; } // Count only the change when a chunk is repeated. t.receivedBytes += chunk.size() - (held != t.chunks.constEnd() ? held->size() : 0); if (t.receivedBytes > m_maxTransferBytes || t.receivedBytes > t.announcedBytes || pendingBufferedBytes() > kMaxPendingBytes) { m_pending.remove(tid); Q_EMIT transferRejected(tid, i18nc("@info:status file transfer refused", "The transfer exceeded the pending memory limit.")); return; } t.chunks.insert(idx, chunk); if (t.chunks.size() < t.total) return; // still waiting on more chunks QByteArray full; full.reserve(int(qMin(t.receivedBytes, m_maxTransferBytes))); for (int i = 0; i < t.total; ++i) { if (!t.chunks.contains(i)) { // missing a chunk despite count matching (duplicate?) - bail out safely return; } full.append(t.chunks.value(i)); } if (full.size() != t.announcedBytes) { m_pending.remove(tid); Q_EMIT transferRejected(tid, i18nc("@info:status file transfer refused", "The received data does not match the announced size.")); return; } // Files now always arrive plain in the clear of their own transport: the // TLS channel they rode is the cipher, so there is no per-file seal to // open. A leftover "encrypted" flag from an older build is ignored. QByteArray payload = full; Q_EMIT fileReceived(t.meta, payload); const QString localPath = saveToDisk(t.meta, payload); if (!localPath.isEmpty()) Q_EMIT fileSaved(t.meta, localPath); else Q_EMIT transferRejected(tid, i18nc("@info:status file transfer refused", "Failed to write the file to disk.")); m_pending.remove(tid); } void FileTransferHandler::pruneStaleTransfers() { const qint64 now = QDateTime::currentMSecsSinceEpoch(); QVector stale; for (auto it = m_pending.constBegin(); it != m_pending.constEnd(); ++it) { if (now - it.value().startedAtMs > kPendingTransferTtlMs) stale.append(it.key()); } for (const auto &tid : stale) { m_pending.remove(tid); Q_EMIT transferRejected(tid, i18nc("@info:status file transfer refused", "The transfer timed out while incomplete.")); } // An offer the user never answered is dropped on the same clock. Nobody is // told about these: there is no transfer yet to refuse. QVector staleOffers; for (auto it = m_offers.constBegin(); it != m_offers.constEnd(); ++it) { if (now - it.value().offeredAtMs > kPendingTransferTtlMs) staleOffers.append(it.key()); } for (const auto &tid : staleOffers) m_offers.remove(tid); } QString FileTransferHandler::saveToDisk(const QJsonObject &meta, const QByteArray &data) const { const QString baseDir = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation); const QString dirPath = baseDir.isEmpty() ? QString(QDir::homePath() + QStringLiteral("/KOutNet/received")) : QString(baseDir + QStringLiteral("/KOutNet")); QDir dir; if (!dir.mkpath(dirPath)) return QString(); // never trust a peer-supplied filename in a disk path - see sanitizeFilename(). const QString filename = sanitizeFilename(meta.value(QStringLiteral("filename")).toString()); QString candidate = dirPath + QLatin1Char('/') + filename; if (QFileInfo::exists(candidate)) { const QFileInfo fi(filename); const QString base = fi.completeBaseName(); const QString ext = fi.suffix(); int n = 1; do { candidate = dirPath + QLatin1Char('/') + base + QStringLiteral("(%1)").arg(n) + (ext.isEmpty() ? QString() : QString(QLatin1Char('.') + ext)); ++n; } while (QFileInfo::exists(candidate)); } // absoluteFilePath() only cleans "." and ".." out of the string, so a symlink // along the way still escaped. Compare the parent: the candidate does not exist. const QString canonicalDir = QFileInfo(dirPath).canonicalFilePath(); const QString candidateDir = QFileInfo(candidate).absolutePath(); if (canonicalDir.isEmpty() || QFileInfo(candidateDir).canonicalFilePath() != canonicalDir) return QString(); // NewOnly, not WriteOnly: something could have created the path since the // exists() loop ran, and failing beats overwriting whatever appeared. QFile out(candidate); if (!out.open(QIODevice::NewOnly)) return QString(); const qint64 written = out.write(data); const bool ok = written == data.size() && out.flush(); out.close(); if (!ok) { // a half-written file is worse than none, and the name is free again out.remove(); return QString(); } return candidate; } } // namespace koutnet