Fix connecting to tx.decrypt.fail

This commit is contained in:
Shadowfacts 2021-06-17 22:58:46 -04:00
parent 8c43bc8a44
commit 1ce48bc77e
1 changed files with 20 additions and 6 deletions

View File

@ -14,6 +14,8 @@ class GeminiProtocol: NWProtocolFramerImplementation {
private var tempStatusCode: GeminiResponseHeader.StatusCode? private var tempStatusCode: GeminiResponseHeader.StatusCode?
private var tempMeta: String? private var tempMeta: String?
private var lastAttemptedMetaLength: Int?
private var lastFoundCR = false
required init(framer: NWProtocolFramer.Instance) { required init(framer: NWProtocolFramer.Instance) {
} }
@ -45,13 +47,21 @@ class GeminiProtocol: NWProtocolFramerImplementation {
return 3 return 3
} }
var attemptedMetaLength: Int?
if tempMeta == nil { if tempMeta == nil {
// Minimum length is 2 bytes, spec does not say meta string is required let min: Int
_ = framer.parseInput(minimumIncompleteLength: 2, maximumLength: 1024 + 2) { (buffer, isComplete) -> Int in // if we previously tried to get the meta but failed (because the <CR><LF> was not found,
// the minimum amount we need before trying to parse is at least 1 or 2 (depending on whether we found the <CR>) 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, guard let buffer = buffer,
buffer.count >= 2 else { return 0 } 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)) let lastPossibleCRIndex = buffer.index(before: buffer.index(before: buffer.endIndex))
var index = buffer.startIndex var index = buffer.startIndex
@ -66,6 +76,10 @@ class GeminiProtocol: NWProtocolFramerImplementation {
} }
if !found { if !found {
if buffer[index] == 13 {
// if we found <CR>, but not <LF>, save that info so that next time we only wait for 1 more byte instead of 2
self.lastFoundCR = true
}
if buffer.count < 1026 { if buffer.count < 1026 {
return 0 return 0
} else { } else {
@ -78,8 +92,8 @@ class GeminiProtocol: NWProtocolFramerImplementation {
} }
} }
guard let meta = tempMeta else { guard let meta = tempMeta else {
if let attempted = attemptedMetaLength { if let attempted = self.lastAttemptedMetaLength {
return attempted + 1 return attempted + (lastFoundCR ? 1 : 2)
} else { } else {
return 2 return 2
} }