diff --git a/bitchat/Localizable.xcstrings b/bitchat/Localizable.xcstrings index e498a20e..7742abb5 100644 --- a/bitchat/Localizable.xcstrings +++ b/bitchat/Localizable.xcstrings @@ -16184,187 +16184,187 @@ } }, "content.delivery.reason.private_media_too_many_fragments" : { - "comment" : "Failure reason when private media exceeds the Android-compatible fragment limit", + "comment" : "Failure reason when private media exceeds the recipient's fragment limit; %lld is that limit", "extractionState" : "manual", "localizations" : { "ar" : { "stringUnit" : { "state" : "translated", - "value" : "الملف كبير جدًا على تطبيق جهة الاتصال هذه (أكثر من 256 جزءًا عبر الشبكة المتداخلة)" + "value" : "الملف كبير جدًا على تطبيق جهة الاتصال هذه (أكثر من %lld جزءًا عبر الشبكة المتداخلة)" } }, "bn" : { "stringUnit" : { "state" : "translated", - "value" : "এই কন্টাক্টের ক্লায়েন্টের জন্য ফাইলটি খুব বড় (256টির বেশি মেশ ফ্র্যাগমেন্ট)" + "value" : "এই কন্টাক্টের ক্লায়েন্টের জন্য ফাইলটি খুব বড় (%lldটির বেশি মেশ ফ্র্যাগমেন্ট)" } }, "de" : { "stringUnit" : { "state" : "translated", - "value" : "Datei ist zu groß für den Client dieses Kontakts (mehr als 256 Mesh-Fragmente)" + "value" : "Datei ist zu groß für den Client dieses Kontakts (mehr als %lld Mesh-Fragmente)" } }, "en" : { "stringUnit" : { "state" : "translated", - "value" : "File is too large for this contact's client (more than 256 mesh fragments)" + "value" : "File is too large for this contact's client (more than %lld mesh fragments)" } }, "es" : { "stringUnit" : { "state" : "translated", - "value" : "El archivo es demasiado grande para el cliente de este contacto (más de 256 fragmentos de malla)" + "value" : "El archivo es demasiado grande para el cliente de este contacto (más de %lld fragmentos de malla)" } }, "fa" : { "stringUnit" : { "state" : "translated", - "value" : "فایل برای کلاینت این مخاطب خیلی بزرگ است (بیش از 256 قطعهٔ مش)" + "value" : "فایل برای کلاینت این مخاطب خیلی بزرگ است (بیش از %lld قطعهٔ مش)" } }, "fil" : { "stringUnit" : { "state" : "translated", - "value" : "Masyadong malaki ang file para sa client ng contact na ito (mahigit 256 mesh fragment)" + "value" : "Masyadong malaki ang file para sa client ng contact na ito (mahigit %lld mesh fragment)" } }, "fr" : { "stringUnit" : { "state" : "translated", - "value" : "Le fichier est trop volumineux pour le client de ce contact (plus de 256 fragments mesh)" + "value" : "Le fichier est trop volumineux pour le client de ce contact (plus de %lld fragments mesh)" } }, "he" : { "stringUnit" : { "state" : "translated", - "value" : "הקובץ גדול מדי עבור הקליינט של איש הקשר הזה (יותר מ-256 מקטעי mesh)" + "value" : "הקובץ גדול מדי עבור הקליינט של איש הקשר הזה (יותר מ-%lld מקטעי mesh)" } }, "hi" : { "stringUnit" : { "state" : "translated", - "value" : "यह फ़ाइल इस संपर्क के क्लाइंट के लिए बहुत बड़ी है (256 से ज़्यादा मेश फ़्रैगमेंट)" + "value" : "यह फ़ाइल इस संपर्क के क्लाइंट के लिए बहुत बड़ी है (%lld से ज़्यादा मेश फ़्रैगमेंट)" } }, "id" : { "stringUnit" : { "state" : "translated", - "value" : "File terlalu besar untuk klien kontak ini (lebih dari 256 fragmen mesh)" + "value" : "File terlalu besar untuk klien kontak ini (lebih dari %lld fragmen mesh)" } }, "it" : { "stringUnit" : { "state" : "translated", - "value" : "Il file è troppo grande per il client di questo contatto (più di 256 frammenti mesh)" + "value" : "Il file è troppo grande per il client di questo contatto (più di %lld frammenti mesh)" } }, "ja" : { "stringUnit" : { "state" : "translated", - "value" : "このファイルはこの連絡先のクライアントには大きすぎます(メッシュフラグメントが256個を超えています)" + "value" : "このファイルはこの連絡先のクライアントには大きすぎます(メッシュフラグメントが%lld個を超えています)" } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "이 연락처의 클라이언트에는 파일이 너무 커요(메시 조각 256개 초과)" + "value" : "이 연락처의 클라이언트에는 파일이 너무 커요(메시 조각 %lld개 초과)" } }, "ms" : { "stringUnit" : { "state" : "translated", - "value" : "Fail terlalu besar untuk klien kenalan ini (lebih daripada 256 fragmen mesh)" + "value" : "Fail terlalu besar untuk klien kenalan ini (lebih daripada %lld fragmen mesh)" } }, "ne" : { "stringUnit" : { "state" : "translated", - "value" : "यो सम्पर्कको क्लाइन्टका लागि फाइल धेरै ठूलो छ (256 भन्दा बढी मेश खण्डहरू)" + "value" : "यो सम्पर्कको क्लाइन्टका लागि फाइल धेरै ठूलो छ (%lld भन्दा बढी मेश खण्डहरू)" } }, "nl" : { "stringUnit" : { "state" : "translated", - "value" : "Het bestand is te groot voor de client van dit contact (meer dan 256 mesh-fragmenten)" + "value" : "Het bestand is te groot voor de client van dit contact (meer dan %lld mesh-fragmenten)" } }, "pl" : { "stringUnit" : { "state" : "translated", - "value" : "Plik jest za duży dla klienta tego kontaktu (ponad 256 fragmentów mesh)" + "value" : "Plik jest za duży dla klienta tego kontaktu (ponad %lld fragmentów mesh)" } }, "pt" : { "stringUnit" : { "state" : "translated", - "value" : "O ficheiro é demasiado grande para o cliente deste contacto (mais de 256 fragmentos da malha)" + "value" : "O ficheiro é demasiado grande para o cliente deste contacto (mais de %lld fragmentos da malha)" } }, "pt-BR" : { "stringUnit" : { "state" : "translated", - "value" : "O arquivo é grande demais para o cliente deste contato (mais de 256 fragmentos da malha)" + "value" : "O arquivo é grande demais para o cliente deste contato (mais de %lld fragmentos da malha)" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Файл слишком большой для клиента этого контакта (больше 256 фрагментов mesh-сети)" + "value" : "Файл слишком большой для клиента этого контакта (больше %lld фрагментов mesh-сети)" } }, "sv" : { "stringUnit" : { "state" : "translated", - "value" : "Filen är för stor för den här kontaktens klient (fler än 256 mesh-fragment)" + "value" : "Filen är för stor för den här kontaktens klient (fler än %lld mesh-fragment)" } }, "ta" : { "stringUnit" : { "state" : "translated", - "value" : "இந்தத் தொடர்பின் கிளையண்டுக்கு இந்தக் கோப்பு மிகப் பெரியது (256-க்கும் மேற்பட்ட மெஷ் துண்டுகள்)" + "value" : "இந்தத் தொடர்பின் கிளையண்டுக்கு இந்தக் கோப்பு மிகப் பெரியது (%lld-க்கும் மேற்பட்ட மெஷ் துண்டுகள்)" } }, "th" : { "stringUnit" : { "state" : "translated", - "value" : "ไฟล์ใหญ่เกินไปสำหรับไคลเอ็นต์ของผู้ติดต่อรายนี้ (เกิน 256 ส่วนย่อยของ mesh)" + "value" : "ไฟล์ใหญ่เกินไปสำหรับไคลเอ็นต์ของผู้ติดต่อรายนี้ (เกิน %lld ส่วนย่อยของ mesh)" } }, "tr" : { "stringUnit" : { "state" : "translated", - "value" : "Dosya bu kişinin istemcisi için çok büyük (256'dan fazla mesh parçası)" + "value" : "Dosya bu kişinin istemcisi için çok büyük (mesh parça sınırı: %lld)" } }, "uk" : { "stringUnit" : { "state" : "translated", - "value" : "Файл завеликий для клієнта цього контакту (понад 256 фрагментів mesh-мережі)" + "value" : "Файл завеликий для клієнта цього контакту (понад %lld фрагментів mesh-мережі)" } }, "ur" : { "stringUnit" : { "state" : "translated", - "value" : "یہ فائل اس رابطے کے کلائنٹ کے لیے بہت بڑی ہے (256 سے زیادہ میش ٹکڑے)" + "value" : "یہ فائل اس رابطے کے کلائنٹ کے لیے بہت بڑی ہے (%lld سے زیادہ میش ٹکڑے)" } }, "vi" : { "stringUnit" : { "state" : "translated", - "value" : "Tệp quá lớn so với ứng dụng của liên hệ này (hơn 256 phân mảnh mesh)" + "value" : "Tệp quá lớn so với ứng dụng của liên hệ này (hơn %lld phân mảnh mesh)" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "文件太大,这位联系人的客户端无法接收(超过 256 个网状网络分片)" + "value" : "文件太大,这位联系人的客户端无法接收(超过 %lld 个网状网络分片)" } }, "zh-Hant" : { "stringUnit" : { "state" : "translated", - "value" : "檔案太大,這位聯絡人的用戶端無法接收(超過 256 個網狀網路分段)" + "value" : "檔案太大,這位聯絡人的用戶端無法接收(超過 %lld 個網狀網路分段)" } } } diff --git a/bitchat/Services/BLE/BLEPrivateMediaSessionStore.swift b/bitchat/Services/BLE/BLEPrivateMediaSessionStore.swift index 461d934c..751f18a0 100644 --- a/bitchat/Services/BLE/BLEPrivateMediaSessionStore.swift +++ b/bitchat/Services/BLE/BLEPrivateMediaSessionStore.swift @@ -5,6 +5,22 @@ struct BLEAuthenticatedPeerStateObservation { let fingerprint: String let sessionGeneration: UUID let capabilities: PeerCapabilities + /// The peer's own reassembly bound, if it advertised one. Bound to the + /// generation like every other field here: a replacement session must + /// re-state its ceiling rather than inherit the previous one. + let maxReassemblyFragments: UInt16? + + init( + fingerprint: String, + sessionGeneration: UUID, + capabilities: PeerCapabilities, + maxReassemblyFragments: UInt16? = nil + ) { + self.fingerprint = fingerprint + self.sessionGeneration = sessionGeneration + self.capabilities = capabilities + self.maxReassemblyFragments = maxReassemblyFragments + } } struct BLEPrivateMediaProofTimeoutMarker { @@ -163,14 +179,16 @@ final class BLEPrivateMediaSessionStore: @unchecked Sendable { for peerID: PeerID, fingerprint: String, generation: UUID, - capabilities: PeerCapabilities + capabilities: PeerCapabilities, + maxReassemblyFragments: UInt16? = nil ) -> [@MainActor (PrivateMediaSendPolicy) -> Void]? { lock.withLock { guard sessionGenerations[peerID] == generation else { return nil } authenticatedStates[peerID] = BLEAuthenticatedPeerStateObservation( fingerprint: fingerprint, sessionGeneration: generation, - capabilities: capabilities + capabilities: capabilities, + maxReassemblyFragments: maxReassemblyFragments ) proofTimeoutMarkers.removeValue(forKey: peerID) proofWatchdogs.removeValue(forKey: peerID) @@ -347,6 +365,22 @@ final class BLEPrivateMediaSessionStore: @unchecked Sendable { } extension BLEPrivateMediaSessionStore { + /// The recipient's advertised reassembly ceiling, or nil when it did not + /// advertise one. + /// + /// Only honoured for an observation pinned to the peer's *current* + /// generation. A ceiling read off a superseded session is a statement by + /// whoever held that session, and after a rekey the counterpart may be a + /// different client entirely — falling back to the type proxy is the + /// conservative answer, not reusing a stale number. + func negotiatedFragmentCeiling(for peerID: PeerID) -> UInt16? { + let inputs = policyInputs(for: peerID) + guard let generation = inputs.sessionGeneration, + let authenticated = inputs.authenticatedState, + authenticated.sessionGeneration == generation else { return nil } + return authenticated.maxReassemblyFragments + } + /// The current generation iff its authenticated peer state proved the /// private-media capability (and, when required, durable receipts). func provenGeneration(for peerID: PeerID, requireReceipts: Bool) -> UUID? { diff --git a/bitchat/Services/BLE/BLEService.swift b/bitchat/Services/BLE/BLEService.swift index edd630e9..dc7374f8 100644 --- a/bitchat/Services/BLE/BLEService.swift +++ b/bitchat/Services/BLE/BLEService.swift @@ -2009,13 +2009,19 @@ final class BLEService: NSObject { // unaffected. Run the same planner the scheduler will use, after route // application, and reject before reserving a transfer slot or writing // any fragment. - // TODO(#1434): negotiate an explicit per-peer fragment limit so a future - // Android client that adopts the encrypted 0x20 path but still caps its - // reassembler can advertise its own ceiling instead of relying on the - // capability/type proxy above. + // The proxy above is now only the fallback: a peer that advertised its + // own ceiling in authenticated `0x21` state has it honoured instead, + // which is what closes #1434. That also means the check can no longer + // be restricted to `fileTransfer` — an advertised ceiling constrains + // encrypted media too, and that is precisely the case (small + // reassembler behind the `0x20` path) the type proxy misses. if let transferId, - let recipientPeerID = PeerID(hexData: packetToSend.recipientID), - packetToSend.type == MessageType.fileTransfer.rawValue { + let recipientPeerID = PeerID(hexData: packetToSend.recipientID) { + let ceiling = BLEFragmentCeilingPolicy.decide( + packetType: packetToSend.type, + isDirectedToPeer: true, + negotiatedCeiling: privateMediaSessions.negotiatedFragmentCeiling(for: recipientPeerID.toShort()) + ) let compatibilityRequest = BLEOutboundFragmentTransferRequest( packet: packetToSend, pad: padForBLE, @@ -2027,17 +2033,20 @@ final class BLEService: NSObject { for: compatibilityRequest, defaultChunkSize: defaultFragmentSize, bleMaxMTU: bleMaxMTU - ), BLEOutboundFragmentPlanner.isPrivateMediaV1Compatible(plan) else { + ), ceiling.admits(fragmentCount: plan.totalFragments) else { SecureLogger.warning( - "Private media rejected: exceeds cross-platform 256-fragment limit", + "Private media rejected: \(String(describing: ceiling.source)) limit of \(ceiling.maxFragments) fragments", category: .security ) TransferProgressManager.shared.rejectBeforeStart( id: transferId, reason: String( - localized: "content.delivery.reason.private_media_too_many_fragments", - defaultValue: "File is too large for this contact's client (more than 256 mesh fragments)", - comment: "Failure reason when private media exceeds the Android-compatible fragment limit" + format: String( + localized: "content.delivery.reason.private_media_too_many_fragments", + defaultValue: "File is too large for this contact's client (more than %lld mesh fragments)", + comment: "Failure reason when private media exceeds the recipient's fragment limit; %lld is that limit" + ), + ceiling.maxFragments ) ) if requiresPrivateMediaAdmission { @@ -4234,7 +4243,12 @@ extension BLEService { let capabilities = localIdentityState.snapshot().advertisedCapabilities let state = AuthenticatedPeerStatePacket( capabilities: capabilities, - signingPublicKey: noiseService.getSigningPublicKeyData() + signingPublicKey: noiseService.getSigningPublicKeyData(), + // Our own reassembler's bound, so a peer sizing a transfer for us + // does not have to infer it from the packet type either. + maxReassemblyFragments: UInt16( + clamping: BLEFragmentAssemblyBuffer.maxReassemblyFragments + ) ) guard let payload = BLENoisePayloadFactory.authenticatedPeerState(state) else { SecureLogger.error("Failed to encode authenticated peer state", category: .security) @@ -4308,7 +4322,8 @@ extension BLEService { for: normalizedPeerID, fingerprint: fingerprint, generation: generation, - capabilities: state.capabilities + capabilities: state.capabilities, + maxReassemblyFragments: state.maxReassemblyFragments ) else { return (false, []) } diff --git a/bitchatTests/Services/BLEFragmentCeilingPolicyTests.swift b/bitchatTests/Services/BLEFragmentCeilingPolicyTests.swift index 385e0239..3120d894 100644 --- a/bitchatTests/Services/BLEFragmentCeilingPolicyTests.swift +++ b/bitchatTests/Services/BLEFragmentCeilingPolicyTests.swift @@ -124,7 +124,7 @@ struct BLEFragmentCeilingPolicyTests { fileTransfer, noiseEncrypted, MessageType.message.rawValue, - MessageType.announce.rawValue, + MessageType.announce.rawValue ] for ceiling in ceilings { diff --git a/bitchatTests/Services/BLEPrivateMediaSessionStoreTests.swift b/bitchatTests/Services/BLEPrivateMediaSessionStoreTests.swift index b04e6c41..f1ca308a 100644 --- a/bitchatTests/Services/BLEPrivateMediaSessionStoreTests.swift +++ b/bitchatTests/Services/BLEPrivateMediaSessionStoreTests.swift @@ -189,4 +189,73 @@ struct BLEPrivateMediaSessionStoreTests { ) #expect(store.markPeerStateSend(for: peer, echo: false)) } + + // MARK: - Negotiated reassembly ceiling + + @Test func negotiatedCeilingIsReadableOnlyForTheGenerationThatStatedIt() { + let store = BLEPrivateMediaSessionStore() + let generation = UUID() + _ = store.beginAuthenticatedGeneration( + for: peer, fingerprint: fingerprint, generation: generation + ) + #expect(store.negotiatedFragmentCeiling(for: peer) == nil) + + _ = store.applyAuthenticatedPeerState( + for: peer, + fingerprint: fingerprint, + generation: generation, + capabilities: [.privateMedia], + maxReassemblyFragments: 128 + ) + #expect(store.negotiatedFragmentCeiling(for: peer) == 128) + + // A rekey replaces the counterpart's session state. The old ceiling + // was a statement by whoever held that session, and the replacement + // may be a different client entirely, so it must not be inherited. + // + // Two independent mechanisms enforce this: `beginAuthenticatedGeneration` + // drops the observation, and the accessor refuses one whose pinned + // generation is not current. Removing either alone still passes; this + // expectation fails once both are gone, which is the invariant it is + // here to hold rather than any single line of it. + _ = store.beginAuthenticatedGeneration( + for: peer, fingerprint: fingerprint, generation: UUID() + ) + #expect(store.negotiatedFragmentCeiling(for: peer) == nil) + } + + @Test func peerStateWithoutACeilingLeavesTheSenderOnTheTypeProxy() { + let store = BLEPrivateMediaSessionStore() + let generation = UUID() + _ = store.beginAuthenticatedGeneration( + for: peer, fingerprint: fingerprint, generation: generation + ) + // Every client released before TLV 0x03 lands here. + _ = store.applyAuthenticatedPeerState( + for: peer, + fingerprint: fingerprint, + generation: generation, + capabilities: [.privateMedia] + ) + #expect(store.negotiatedFragmentCeiling(for: peer) == nil) + } + + @Test func clearingTheSessionDropsTheNegotiatedCeiling() { + let store = BLEPrivateMediaSessionStore() + let generation = UUID() + _ = store.beginAuthenticatedGeneration( + for: peer, fingerprint: fingerprint, generation: generation + ) + _ = store.applyAuthenticatedPeerState( + for: peer, + fingerprint: fingerprint, + generation: generation, + capabilities: [.privateMedia], + maxReassemblyFragments: 512 + ) + #expect(store.negotiatedFragmentCeiling(for: peer) == 512) + + _ = store.clearSession(for: peer) + #expect(store.negotiatedFragmentCeiling(for: peer) == nil) + } }