WebChunkCache.swift 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2018-2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. import Foundation
  21. import CocoaLumberjackSwift
  22. enum ChunkCacheError: Error {
  23. case invalidSequenceNumber
  24. case timeTravelForewards
  25. case timeTravelBackwards
  26. }
  27. class WebChunkCache: NSObject, NSCoding {
  28. private var _sequenceNumber: WebSequenceNumber
  29. private var _byteLength: Int = 0
  30. private var cache: [[UInt8]?] = [[UInt8]?]()
  31. init(sequenceNumber:WebSequenceNumber) {
  32. _sequenceNumber = sequenceNumber
  33. }
  34. func sequenceNumber() -> WebSequenceNumber {
  35. return _sequenceNumber
  36. }
  37. func byteLength() -> Int {
  38. return _byteLength
  39. }
  40. func chunks() -> [[UInt8]?] {
  41. return cache
  42. }
  43. func transfer(fromCache: [[UInt8]?]) {
  44. DDLogVerbose("Threema Web: Web Chunk Cache --> start transfer cache")
  45. let tmpCache = cache.compactMap{$0}
  46. self.cache = tmpCache
  47. for chunk in fromCache {
  48. if chunk != nil {
  49. append(chunk: chunk)
  50. }
  51. }
  52. DDLogVerbose("Threema Web: Web Chunk Cache --> end transfer cache")
  53. }
  54. func append(chunk: [UInt8]?) {
  55. if chunk != nil {
  56. _byteLength = _byteLength + chunk!.count
  57. }
  58. cache.append(chunk)
  59. _ = _sequenceNumber.increment()
  60. DDLogVerbose("Threema Web: Web Chunk Cache --> \(_sequenceNumber.value)")
  61. }
  62. func prune(theirSequenceNumber: UInt32) throws {
  63. if sequenceNumber().isValid(other: UInt64(theirSequenceNumber)) == false {
  64. // error: Remote sent us an invalid sequence number
  65. throw ChunkCacheError.invalidSequenceNumber
  66. }
  67. // Calculate the slice start index for the chunk cache
  68. // Important: Our sequence number is one chunk ahead!
  69. let offset: Int64 = Int64(theirSequenceNumber) - Int64(_sequenceNumber.value)
  70. if offset > 0 {
  71. // error: Remote travelled through time and acknowledged a chunk which is in the future
  72. ValidationLogger.shared()?.logString("Threema Web: Prune Cache Error timeTravelForewards --> their: \(Int64(theirSequenceNumber)) my: \(Int64(_sequenceNumber.value))")
  73. throw ChunkCacheError.timeTravelForewards
  74. }
  75. else if -offset > cache.count {
  76. // error: Remote travelled back in time and acknowledged a chunk it has already acknowledged
  77. ValidationLogger.shared()?.logString("Threema Web: Prune Cache Error timeTravelBackwards --> their: \(Int64(theirSequenceNumber)) my: \(Int64(cache.count))")
  78. throw ChunkCacheError.timeTravelBackwards
  79. }
  80. ValidationLogger.shared()?.logString("Threema Web: Prune Cache --> their: \(Int64(theirSequenceNumber)) my: \(Int64(_sequenceNumber.value))")
  81. let endOffset = Int(Int64(cache.count) + offset)
  82. if endOffset == cache.count {
  83. cache = [[UInt8]]()
  84. _byteLength = 0
  85. } else {
  86. let removedChunks = cache[..<endOffset]
  87. let tmpCache = cache
  88. cache = Array(tmpCache.dropFirst(endOffset))
  89. for chunk in removedChunks {
  90. if chunk != nil {
  91. _byteLength = _byteLength - chunk!.count
  92. }
  93. }
  94. }
  95. }
  96. required init?(coder aDecoder: NSCoder) {
  97. // super.init(coder:) is optional, see notes below
  98. self._sequenceNumber = aDecoder.decodeObject(forKey: "_sequenceNumber") as! WebSequenceNumber
  99. self._byteLength = aDecoder.decodeInteger(forKey: "_byteLength")
  100. let tmpCache = aDecoder.decodeObject(forKey: "cache")
  101. if tmpCache is [[UInt8]?] {
  102. self.cache = aDecoder.decodeObject(forKey: "cache") as! [[UInt8]?]
  103. } else {
  104. self.cache = [[UInt8]?]()
  105. }
  106. }
  107. func encode(with aCoder: NSCoder) {
  108. // super.encodeWithCoder(aCoder) is optional, see notes below
  109. aCoder.encode(_sequenceNumber, forKey: "_sequenceNumber")
  110. aCoder.encode(_byteLength, forKey: "_byteLength")
  111. aCoder.encode(cache, forKey: "cache")
  112. }
  113. }