From 1ce48bc77e5bb86b217f55073e540f418386ef6f Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Thu, 17 Jun 2021 22:58:46 -0400 Subject: [PATCH] Fix connecting to tx.decrypt.fail --- GeminiProtocol/GeminiProtocol.swift | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/GeminiProtocol/GeminiProtocol.swift b/GeminiProtocol/GeminiProtocol.swift index 569b71f..649c508 100644 --- a/GeminiProtocol/GeminiProtocol.swift +++ b/GeminiProtocol/GeminiProtocol.swift @@ -14,6 +14,8 @@ class GeminiProtocol: NWProtocolFramerImplementation { private var tempStatusCode: GeminiResponseHeader.StatusCode? private var tempMeta: String? + private var lastAttemptedMetaLength: Int? + private var lastFoundCR = false required init(framer: NWProtocolFramer.Instance) { } @@ -45,13 +47,21 @@ class GeminiProtocol: NWProtocolFramerImplementation { return 3 } - var attemptedMetaLength: Int? if tempMeta == nil { - // Minimum length is 2 bytes, spec does not say meta string is required - _ = framer.parseInput(minimumIncompleteLength: 2, maximumLength: 1024 + 2) { (buffer, isComplete) -> Int in + let min: Int + // if we previously tried to get the meta but failed (because the was not found, + // the minimum amount we need before trying to parse is at least 1 or 2 (depending on whether we found the ) bytes more + if let lastAttemptedMetaLength = lastAttemptedMetaLength { + min = lastAttemptedMetaLength + (lastFoundCR ? 1 : 2) + } else { + // Minimum length is 2 bytes, spec does not say meta string is required + min = 2 + } + _ = framer.parseInput(minimumIncompleteLength: min, maximumLength: 1024 + 2) { (buffer, isComplete) -> Int in guard let buffer = buffer, buffer.count >= 2 else { return 0 } - attemptedMetaLength = buffer.count + print("got count: \(buffer.count)") + self.lastAttemptedMetaLength = buffer.count let lastPossibleCRIndex = buffer.index(before: buffer.index(before: buffer.endIndex)) var index = buffer.startIndex @@ -66,6 +76,10 @@ class GeminiProtocol: NWProtocolFramerImplementation { } if !found { + if buffer[index] == 13 { + // if we found , but not , save that info so that next time we only wait for 1 more byte instead of 2 + self.lastFoundCR = true + } if buffer.count < 1026 { return 0 } else { @@ -78,8 +92,8 @@ class GeminiProtocol: NWProtocolFramerImplementation { } } guard let meta = tempMeta else { - if let attempted = attemptedMetaLength { - return attempted + 1 + if let attempted = self.lastAttemptedMetaLength { + return attempted + (lastFoundCR ? 1 : 2) } else { return 2 }