WebUpdateConnectionInfoRequest.swift 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. class WebUpdateConnectionInfoRequest: NSObject, NSCoding {
  23. let id: Data
  24. let resume: WebConnection?
  25. init(message:WebAbstractMessage) {
  26. let data = message.data as! [AnyHashable: Any?]
  27. id = data["id"] as! Data
  28. if let tmpResume = data["resume"] as? [String: Any] {
  29. resume = WebConnection.init(connection: tmpResume)
  30. } else {
  31. resume = nil
  32. }
  33. }
  34. func maybeResume(session: WCSession) {
  35. if let connectionInfoResponse = session.connectionInfoResponse() {
  36. if connectionInfoResponse.id != id {
  37. ValidationLogger.shared().logString("Threema Web: Wrong connection id, stop session.")
  38. session.stop(close: true, forget: false, sendDisconnect: true, reason: .error)
  39. return
  40. }
  41. if resume != nil, let context = session.connectionContext() {
  42. if context.previousConnectionContext?.connectionId() == resume!.id {
  43. do {
  44. // should be previousContext
  45. try context.previousConnectionContext?.prune(theirSequenceNumber: resume!.sequenceNumber!)
  46. }
  47. catch {
  48. // do error stuff
  49. ValidationLogger.shared().logString("Threema Web: Could not prune cache: \(error).")
  50. session.stop(close: true, forget: false, sendDisconnect: true, reason: .error)
  51. return
  52. }
  53. if session.connectionStatus() == .ready {
  54. if context.previousConnectionContext != nil {
  55. context.transfer(fromCache: context.previousConnectionContext!.chunkCache.chunks())
  56. ValidationLogger.shared().logString("Threema Web: Transfer \(context.chunkCache.chunks().count) chunks.")
  57. for chunk in context.chunkCache.chunks() {
  58. session.sendChunk(chunk: chunk!, msgpack: nil, connectionInfo: false)
  59. }
  60. context.updateUnchunker(oldUnchunker: context.previousConnectionContext!.unchunker)
  61. context.previousConnectionContext = nil
  62. }
  63. session.messageQueue.processQueue()
  64. context.runTimer()
  65. }
  66. ValidationLogger.shared().logString("Threema Web: Resume connection.")
  67. let responseBatteryStatus = WebBatteryStatusUpdate.init()
  68. session.sendMessageToWeb(blacklisted: true, msgpack: responseBatteryStatus.messagePack())
  69. DDLogVerbose("Threema Web: MessagePack -> Send update/batteryStatus")
  70. return
  71. }
  72. }
  73. if resume == nil {
  74. ValidationLogger.shared().logString("Threema Web: Resume is nil.")
  75. }
  76. if session.connectionContext() == nil {
  77. ValidationLogger.shared().logString("Threema Web: Connection context is nil.")
  78. }
  79. // do not resume
  80. session.clearAllRequestedLists()
  81. if session.connectionStatus() == .ready {
  82. ValidationLogger.shared().logString("Threema Web: Connection state is ready -> process queue and reset previous connection context.")
  83. session.messageQueue.processQueue()
  84. session.connectionContext()?.previousConnectionContext = nil
  85. session.connectionContext()?.runTimer()
  86. }
  87. return
  88. }
  89. }
  90. required init?(coder aDecoder: NSCoder) {
  91. self.id = aDecoder.decodeObject(forKey: "id") as! Data
  92. self.resume = aDecoder.decodeObject(forKey: "resume") as? WebConnection
  93. }
  94. func encode(with aCoder: NSCoder) {
  95. aCoder.encode(id, forKey: "id")
  96. aCoder.encode(resume, forKey: "resume")
  97. }
  98. }
  99. class WebConnection: NSObject, NSCoding {
  100. var id: Data
  101. var sequenceNumber: UInt32? // chunk id
  102. init(connection:[String: Any]) {
  103. id = connection["id"] as! Data
  104. if connection["sequenceNumber"] != nil {
  105. sequenceNumber = WebConnection.convertToUInt32(sn: connection["sequenceNumber"]!)
  106. }
  107. }
  108. // MARK: NSCoding
  109. required public init?(coder aDecoder: NSCoder) {
  110. self.id = aDecoder.decodeObject(forKey: "id") as! Data
  111. self.sequenceNumber = UInt32(aDecoder.decodeInt32(forKey: "sequenceNumber"))
  112. }
  113. public func encode(with aCoder: NSCoder) {
  114. aCoder.encode(id, forKey: "id")
  115. if sequenceNumber != nil {
  116. aCoder.encode(Int32(sequenceNumber!), forKey: "sequenceNumber")
  117. }
  118. }
  119. func objectDict() -> [String: Any] {
  120. return ["id": id, "sequenceNumber": sequenceNumber ?? 0]
  121. }
  122. class func convertToUInt32(sn: Any) -> UInt32 {
  123. var converted: UInt32 = 0
  124. if let sq = sn as? UInt8 {
  125. converted = UInt32(sq)
  126. }
  127. else if let sq = sn as? Int8 {
  128. converted = UInt32(sq)
  129. }
  130. else if let sq = sn as? UInt16 {
  131. converted = UInt32(sq)
  132. }
  133. else if let sq = sn as? Int16 {
  134. converted = UInt32(sq)
  135. }
  136. else if let sq = sn as? UInt32 {
  137. converted = sq
  138. }
  139. else if let sq = sn as? Int32 {
  140. converted = UInt32(sq)
  141. }
  142. else if let sq = sn as? UInt64 {
  143. if sq > UINT32_MAX {
  144. // error
  145. } else {
  146. converted = UInt32(sq)
  147. }
  148. }
  149. else if let sq = sn as? Int64 {
  150. if sq > UINT32_MAX {
  151. // error
  152. } else {
  153. converted = UInt32(sq)
  154. }
  155. }
  156. else {
  157. // error
  158. }
  159. return converted
  160. }
  161. }
  162. extension Data {
  163. /// Hexadecimal string representation of `Data` object.
  164. var hexadecimal: String {
  165. return map { String(format: "%02x", $0) }
  166. .joined()
  167. }
  168. }