NCNetworking.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. //
  2. // NCNetworking.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 23/10/19.
  6. // Copyright © 2019 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import UIKit
  24. import OpenSSL
  25. import NextcloudKit
  26. import Alamofire
  27. import Queuer
  28. #if EXTENSION_FILE_PROVIDER_EXTENSION || EXTENSION_WIDGET
  29. @objc protocol uploadE2EEDelegate: AnyObject { }
  30. #endif
  31. @objc protocol NCNetworkingDelegate {
  32. func downloadProgress(_ progress: Float, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask)
  33. func uploadProgress(_ progress: Float, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask)
  34. func downloadComplete(fileName: String, serverUrl: String, etag: String?, date: Date?, dateLastModified: Date?, length: Int64, task: URLSessionTask, error: NKError)
  35. func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: Date?, size: Int64, task: URLSessionTask, error: NKError)
  36. }
  37. @objc protocol ClientCertificateDelegate {
  38. func onIncorrectPassword()
  39. func didAskForClientCertificate()
  40. }
  41. @objcMembers
  42. class NCNetworking: NSObject, NKCommonDelegate {
  43. public static let shared: NCNetworking = {
  44. let instance = NCNetworking()
  45. NotificationCenter.default.addObserver(instance, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
  46. return instance
  47. }()
  48. public struct TransferInForegorund {
  49. var ocId: String
  50. var progress: Float
  51. }
  52. struct FileNameServerUrl: Hashable {
  53. var fileName: String
  54. var serverUrl: String
  55. }
  56. let utilityFileSystem = NCUtilityFileSystem()
  57. let utility = NCUtility()
  58. var lastReachability: Bool = true
  59. var networkReachability: NKCommon.TypeReachability?
  60. let downloadRequest = ThreadSafeDictionary<String, DownloadRequest>()
  61. let uploadRequest = ThreadSafeDictionary<String, UploadRequest>()
  62. let uploadMetadataInBackground = ThreadSafeDictionary<FileNameServerUrl, tableMetadata>()
  63. let downloadMetadataInBackground = ThreadSafeDictionary<FileNameServerUrl, tableMetadata>()
  64. var transferInForegorund: TransferInForegorund?
  65. weak var delegate: NCNetworkingDelegate?
  66. weak var certificateDelegate: ClientCertificateDelegate?
  67. var p12Data: Data?
  68. var p12Password: String?
  69. let transferInError = ThreadSafeDictionary<String, Int>()
  70. func transferInError(ocId: String) {
  71. if let counter = self.transferInError[ocId] {
  72. self.transferInError[ocId] = counter + 1
  73. } else {
  74. self.transferInError[ocId] = 1
  75. }
  76. }
  77. func removeTransferInError(ocId: String) {
  78. self.transferInError.removeValue(forKey: ocId)
  79. }
  80. lazy var nkBackground: NKBackground = {
  81. let nckb = NKBackground(nkCommonInstance: NextcloudKit.shared.nkCommonInstance)
  82. return nckb
  83. }()
  84. public let sessionMaximumConnectionsPerHost = 5
  85. public let sessionDownloadBackground: String = "com.nextcloud.session.download.background"
  86. public let sessionUploadBackground: String = "com.nextcloud.session.upload.background"
  87. public let sessionUploadBackgroundWWan: String = "com.nextcloud.session.upload.backgroundWWan"
  88. public let sessionUploadBackgroundExtension: String = "com.nextcloud.session.upload.extension"
  89. public lazy var sessionManagerDownloadBackground: URLSession = {
  90. let configuration = URLSessionConfiguration.background(withIdentifier: sessionDownloadBackground)
  91. configuration.allowsCellularAccess = true
  92. configuration.sessionSendsLaunchEvents = true
  93. configuration.isDiscretionary = false
  94. configuration.httpMaximumConnectionsPerHost = sessionMaximumConnectionsPerHost
  95. configuration.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData
  96. configuration.httpCookieStorage = HTTPCookieStorage.sharedCookieStorage(forGroupContainerIdentifier: NCBrandOptions.shared.capabilitiesGroup)
  97. let session = URLSession(configuration: configuration, delegate: nkBackground, delegateQueue: OperationQueue.main)
  98. return session
  99. }()
  100. public lazy var sessionManagerUploadBackground: URLSession = {
  101. let configuration = URLSessionConfiguration.background(withIdentifier: sessionUploadBackground)
  102. configuration.allowsCellularAccess = true
  103. configuration.sessionSendsLaunchEvents = true
  104. configuration.isDiscretionary = false
  105. configuration.httpMaximumConnectionsPerHost = sessionMaximumConnectionsPerHost
  106. configuration.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData
  107. configuration.httpCookieStorage = HTTPCookieStorage.sharedCookieStorage(forGroupContainerIdentifier: NCBrandOptions.shared.capabilitiesGroup)
  108. let session = URLSession(configuration: configuration, delegate: nkBackground, delegateQueue: OperationQueue.main)
  109. return session
  110. }()
  111. public lazy var sessionManagerUploadBackgroundWWan: URLSession = {
  112. let configuration = URLSessionConfiguration.background(withIdentifier: sessionUploadBackgroundWWan)
  113. configuration.allowsCellularAccess = false
  114. configuration.sessionSendsLaunchEvents = true
  115. configuration.isDiscretionary = false
  116. configuration.httpMaximumConnectionsPerHost = sessionMaximumConnectionsPerHost
  117. configuration.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData
  118. configuration.httpCookieStorage = HTTPCookieStorage.sharedCookieStorage(forGroupContainerIdentifier: NCBrandOptions.shared.capabilitiesGroup)
  119. let session = URLSession(configuration: configuration, delegate: nkBackground, delegateQueue: OperationQueue.main)
  120. return session
  121. }()
  122. public lazy var sessionManagerUploadBackgroundExtension: URLSession = {
  123. let configuration = URLSessionConfiguration.background(withIdentifier: sessionUploadBackgroundExtension)
  124. configuration.allowsCellularAccess = true
  125. configuration.sessionSendsLaunchEvents = true
  126. configuration.isDiscretionary = false
  127. configuration.httpMaximumConnectionsPerHost = sessionMaximumConnectionsPerHost
  128. configuration.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData
  129. configuration.sharedContainerIdentifier = NCBrandOptions.shared.capabilitiesGroup
  130. configuration.httpCookieStorage = HTTPCookieStorage.sharedCookieStorage(forGroupContainerIdentifier: NCBrandOptions.shared.capabilitiesGroup)
  131. let session = URLSession(configuration: configuration, delegate: nkBackground, delegateQueue: OperationQueue.main)
  132. return session
  133. }()
  134. // REQUESTS
  135. var requestsUnifiedSearch: [DataRequest] = []
  136. // OPERATIONQUEUE
  137. let downloadThumbnailQueue = Queuer(name: "downloadThumbnailQueue", maxConcurrentOperationCount: 10, qualityOfService: .default)
  138. let downloadThumbnailActivityQueue = Queuer(name: "downloadThumbnailActivityQueue", maxConcurrentOperationCount: 10, qualityOfService: .default)
  139. let downloadThumbnailTrashQueue = Queuer(name: "downloadThumbnailTrashQueue", maxConcurrentOperationCount: 10, qualityOfService: .default)
  140. let unifiedSearchQueue = Queuer(name: "unifiedSearchQueue", maxConcurrentOperationCount: 1, qualityOfService: .default)
  141. let saveLivePhotoQueue = Queuer(name: "saveLivePhotoQueue", maxConcurrentOperationCount: 1, qualityOfService: .default)
  142. let downloadQueue = Queuer(name: "downloadQueue", maxConcurrentOperationCount: NCBrandOptions.shared.maxConcurrentOperationDownload, qualityOfService: .default)
  143. let downloadAvatarQueue = Queuer(name: "downloadAvatarQueue", maxConcurrentOperationCount: 10, qualityOfService: .default)
  144. let convertLivePhotoQueue = Queuer(name: "convertLivePhotoQueue", maxConcurrentOperationCount: 10, qualityOfService: .default)
  145. // MARK: - init
  146. override init() {
  147. super.init()
  148. getActiveAccountCertificate()
  149. NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeUser), object: nil, queue: nil) { _ in
  150. self.getActiveAccountCertificate()
  151. }
  152. #if EXTENSION
  153. print("Start Background Upload Extension: ", sessionUploadBackgroundExtension)
  154. #else
  155. print("Start Background Download: ", sessionManagerDownloadBackground)
  156. print("Start Background Upload: ", sessionManagerUploadBackground)
  157. print("Start Background Upload WWan: ", sessionManagerUploadBackgroundWWan)
  158. #endif
  159. }
  160. // MARK: - NotificationCenter
  161. func applicationDidEnterBackground() {
  162. self.transferInError.removeAll()
  163. }
  164. // MARK: - Communication Delegate
  165. func networkReachabilityObserver(_ typeReachability: NKCommon.TypeReachability) {
  166. if typeReachability == NKCommon.TypeReachability.reachableCellular || typeReachability == NKCommon.TypeReachability.reachableEthernetOrWiFi {
  167. if !lastReachability {
  168. #if !EXTENSION
  169. NCService().startRequestServicesServer()
  170. #endif
  171. }
  172. lastReachability = true
  173. } else {
  174. if lastReachability {
  175. let error = NKError(errorCode: NCGlobal.shared.errorNetworkNotAvailable, errorDescription: "")
  176. NCContentPresenter().messageNotification("_network_not_available_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info)
  177. }
  178. lastReachability = false
  179. }
  180. networkReachability = typeReachability
  181. }
  182. func authenticationChallenge(_ session: URLSession,
  183. didReceive challenge: URLAuthenticationChallenge,
  184. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  185. if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate {
  186. DispatchQueue.main.async {
  187. if let p12Data = self.p12Data,
  188. let cert = (p12Data, self.p12Password) as? UserCertificate,
  189. let pkcs12 = try? PKCS12(pkcs12Data: cert.data, password: cert.password, onIncorrectPassword: {
  190. self.certificateDelegate?.onIncorrectPassword()
  191. }) {
  192. let creds = PKCS12.urlCredential(for: pkcs12)
  193. completionHandler(URLSession.AuthChallengeDisposition.useCredential, creds)
  194. } else {
  195. self.certificateDelegate?.didAskForClientCertificate()
  196. completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil)
  197. }
  198. }
  199. } else {
  200. DispatchQueue.global().async {
  201. self.checkTrustedChallenge(session, didReceive: challenge, completionHandler: completionHandler)
  202. }
  203. }
  204. }
  205. func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
  206. #if !EXTENSION
  207. if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let completionHandler = appDelegate.backgroundSessionCompletionHandler {
  208. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Called urlSessionDidFinishEvents for Background URLSession")
  209. appDelegate.backgroundSessionCompletionHandler = nil
  210. completionHandler()
  211. }
  212. #endif
  213. }
  214. // MARK: -
  215. func cancelAllQueue() {
  216. downloadQueue.cancelAll()
  217. downloadThumbnailQueue.cancelAll()
  218. downloadThumbnailActivityQueue.cancelAll()
  219. downloadThumbnailTrashQueue.cancelAll()
  220. downloadAvatarQueue.cancelAll()
  221. unifiedSearchQueue.cancelAll()
  222. saveLivePhotoQueue.cancelAll()
  223. convertLivePhotoQueue.cancelAll()
  224. }
  225. func cancelAllTask() {
  226. cancelAllQueue()
  227. cancelDataTask()
  228. cancelDownloadTasks()
  229. cancelUploadTasks()
  230. cancelDownloadBackgroundTask()
  231. cancelUploadBackgroundTask()
  232. }
  233. // MARK: - Pinning check
  234. public func checkTrustedChallenge(_ session: URLSession,
  235. didReceive challenge: URLAuthenticationChallenge,
  236. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  237. let protectionSpace: URLProtectionSpace = challenge.protectionSpace
  238. let directoryCertificate = utilityFileSystem.directoryCertificates
  239. let host = challenge.protectionSpace.host
  240. let certificateSavedPath = directoryCertificate + "/" + host + ".der"
  241. var isTrusted: Bool
  242. if let trust: SecTrust = protectionSpace.serverTrust,
  243. let certificates = (SecTrustCopyCertificateChain(trust) as? [SecCertificate]),
  244. let certificate = certificates.first {
  245. // extarct certificate txt
  246. saveX509Certificate(certificate, host: host, directoryCertificate: directoryCertificate)
  247. let isServerTrusted = SecTrustEvaluateWithError(trust, nil)
  248. let certificateCopyData = SecCertificateCopyData(certificate)
  249. let data = CFDataGetBytePtr(certificateCopyData)
  250. let size = CFDataGetLength(certificateCopyData)
  251. let certificateData = NSData(bytes: data, length: size)
  252. certificateData.write(toFile: directoryCertificate + "/" + host + ".tmp", atomically: true)
  253. if isServerTrusted {
  254. isTrusted = true
  255. } else if let certificateDataSaved = NSData(contentsOfFile: certificateSavedPath), certificateData.isEqual(to: certificateDataSaved as Data) {
  256. isTrusted = true
  257. } else {
  258. isTrusted = false
  259. }
  260. } else {
  261. isTrusted = false
  262. }
  263. if isTrusted {
  264. completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
  265. } else {
  266. #if !EXTENSION
  267. DispatchQueue.main.async { (UIApplication.shared.delegate as? AppDelegate)?.trustCertificateError(host: host) }
  268. #endif
  269. completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil)
  270. }
  271. }
  272. func writeCertificate(host: String) {
  273. let directoryCertificate = utilityFileSystem.directoryCertificates
  274. let certificateAtPath = directoryCertificate + "/" + host + ".tmp"
  275. let certificateToPath = directoryCertificate + "/" + host + ".der"
  276. if !utilityFileSystem.copyFile(atPath: certificateAtPath, toPath: certificateToPath) {
  277. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Write certificare error")
  278. }
  279. }
  280. func saveX509Certificate(_ certificate: SecCertificate, host: String, directoryCertificate: String) {
  281. let certNamePathTXT = directoryCertificate + "/" + host + ".txt"
  282. let data: CFData = SecCertificateCopyData(certificate)
  283. let mem = BIO_new_mem_buf(CFDataGetBytePtr(data), Int32(CFDataGetLength(data)))
  284. let x509cert = d2i_X509_bio(mem, nil)
  285. if x509cert == nil {
  286. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] OpenSSL couldn't parse X509 Certificate")
  287. } else {
  288. // save details
  289. if FileManager.default.fileExists(atPath: certNamePathTXT) {
  290. do {
  291. try FileManager.default.removeItem(atPath: certNamePathTXT)
  292. } catch { }
  293. }
  294. let fileCertInfo = fopen(certNamePathTXT, "w")
  295. if fileCertInfo != nil {
  296. let output = BIO_new_fp(fileCertInfo, BIO_NOCLOSE)
  297. X509_print_ex(output, x509cert, UInt(XN_FLAG_COMPAT), UInt(X509_FLAG_COMPAT))
  298. BIO_free(output)
  299. }
  300. fclose(fileCertInfo)
  301. X509_free(x509cert)
  302. }
  303. BIO_free(mem)
  304. }
  305. func checkPushNotificationServerProxyCertificateUntrusted(viewController: UIViewController?,
  306. completion: @escaping (_ error: NKError) -> Void) {
  307. guard let host = URL(string: NCBrandOptions.shared.pushNotificationServerProxy)?.host else { return }
  308. NextcloudKit.shared.checkServer(serverUrl: NCBrandOptions.shared.pushNotificationServerProxy) { error in
  309. guard error == .success else {
  310. completion(.success)
  311. return
  312. }
  313. if error == .success {
  314. NCNetworking.shared.writeCertificate(host: host)
  315. completion(error)
  316. } else if error.errorCode == NSURLErrorServerCertificateUntrusted {
  317. let alertController = UIAlertController(title: NSLocalizedString("_ssl_certificate_untrusted_", comment: ""), message: NSLocalizedString("_connect_server_anyway_", comment: ""), preferredStyle: .alert)
  318. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
  319. NCNetworking.shared.writeCertificate(host: host)
  320. completion(.success)
  321. }))
  322. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in
  323. completion(error)
  324. }))
  325. alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
  326. if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController,
  327. let vcCertificateDetails = navigationController.topViewController as? NCViewCertificateDetails {
  328. vcCertificateDetails.host = host
  329. viewController?.present(navigationController, animated: true)
  330. }
  331. }))
  332. viewController?.present(alertController, animated: true)
  333. }
  334. }
  335. }
  336. private func getActiveAccountCertificate() {
  337. if let account = NCManageDatabase.shared.getActiveAccount()?.account {
  338. (self.p12Data, self.p12Password) = NCKeychain().getClientCertificate(account: account)
  339. }
  340. }
  341. }