NCNetworking.swift 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. //
  2. // NCNetworking.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 23/10/19.
  6. // Copyright © 2018 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 Foundation
  24. import OpenSSL
  25. import NCCommunication
  26. @objc public protocol NCNetworkingDelegate {
  27. @objc optional func downloadProgress(_ progress: Double, fileName: String, ServerUrl: String, session: URLSession, task: URLSessionTask)
  28. @objc optional func uploadProgress(_ progress: Double, fileName: String, ServerUrl: String, session: URLSession, task: URLSessionTask)
  29. @objc optional func downloadComplete(fileName: String, serverUrl: String, etag: String?, date: NSDate?, dateLastModified: NSDate?, length: Double, description: String?, error: Error?, statusCode: Int)
  30. @objc optional func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate? ,description: String?, error: Error?, statusCode: Int)
  31. }
  32. @objc class NCNetworking: NSObject, NCCommunicationCommonDelegate {
  33. @objc public static let sharedInstance: NCNetworking = {
  34. let instance = NCNetworking()
  35. return instance
  36. }()
  37. var account = ""
  38. // Protocol
  39. var delegate: NCNetworkingDelegate?
  40. //MARK: - Setup
  41. @objc public func setup(account: String, delegate: NCNetworkingDelegate?) {
  42. self.account = account
  43. self.delegate = delegate
  44. }
  45. //MARK: - Communication Delegate
  46. func authenticationChallenge(_ challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  47. if NCNetworking.sharedInstance.checkTrustedChallenge(challenge: challenge, directoryCertificate: CCUtility.getDirectoryCerificates()) {
  48. completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential.init(trust: challenge.protectionSpace.serverTrust!))
  49. } else {
  50. completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil)
  51. }
  52. }
  53. func downloadProgress(_ progress: Double, fileName: String, ServerUrl: String, session: URLSession, task: URLSessionTask) {
  54. delegate?.downloadProgress?(progress, fileName: fileName, ServerUrl: ServerUrl, session: session, task: task)
  55. }
  56. func uploadProgress(_ progress: Double, fileName: String, ServerUrl: String, session: URLSession, task: URLSessionTask) {
  57. delegate?.uploadProgress?(progress, fileName: fileName, ServerUrl: ServerUrl, session: session, task: task)
  58. }
  59. func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate?, description: String?, error: Error?, statusCode: Int) {
  60. delegate?.uploadComplete?(fileName: fileName, serverUrl: serverUrl, ocId: ocId, etag: etag, date: date, description: description, error: error, statusCode: statusCode)
  61. }
  62. func downloadComplete(fileName: String, serverUrl: String, etag: String?, date: NSDate?, dateLastModified: NSDate?, length: Double, description: String?, error: Error?, statusCode: Int) {
  63. delegate?.downloadComplete?(fileName: fileName, serverUrl: serverUrl, etag: etag, date: date, dateLastModified: dateLastModified, length: length, description: description, error: error, statusCode: statusCode)
  64. }
  65. //MARK: - Pinning check
  66. @objc func checkTrustedChallenge(challenge: URLAuthenticationChallenge, directoryCertificate: String) -> Bool {
  67. var trusted = false
  68. let protectionSpace: URLProtectionSpace = challenge.protectionSpace
  69. let directoryCertificateUrl = URL.init(fileURLWithPath: directoryCertificate)
  70. if let trust: SecTrust = protectionSpace.serverTrust {
  71. saveX509Certificate(trust, certName: "tmp.der", directoryCertificate: directoryCertificate)
  72. do {
  73. let directoryContents = try FileManager.default.contentsOfDirectory(at: directoryCertificateUrl, includingPropertiesForKeys: nil)
  74. let certTmpPath = directoryCertificate+"/"+"tmp.der"
  75. for file in directoryContents {
  76. let certPath = file.path
  77. if certPath == certTmpPath { continue }
  78. if FileManager.default.contentsEqual(atPath:certTmpPath, andPath: certPath) {
  79. trusted = true
  80. break
  81. }
  82. }
  83. } catch { print(error) }
  84. }
  85. return trusted
  86. }
  87. @objc func wrtiteCertificate(directoryCertificate: String) {
  88. let certificateAtPath = directoryCertificate + "/tmp.der"
  89. let certificateToPath = directoryCertificate + "/" + CCUtility.getTimeIntervalSince197() + ".der"
  90. do {
  91. try FileManager.default.moveItem(atPath: certificateAtPath, toPath: certificateToPath)
  92. } catch { }
  93. }
  94. private func saveX509Certificate(_ trust: SecTrust, certName: String, directoryCertificate: String) {
  95. let currentServerCert = secTrustGetLeafCertificate(trust)
  96. let certNamePath = directoryCertificate + "/" + certName
  97. let data: CFData = SecCertificateCopyData(currentServerCert!)
  98. let mem = BIO_new_mem_buf(CFDataGetBytePtr(data), Int32(CFDataGetLength(data)))
  99. let x509cert = d2i_X509_bio(mem, nil)
  100. BIO_free(mem)
  101. if x509cert == nil {
  102. print("[LOG] OpenSSL couldn't parse X509 Certificate")
  103. } else {
  104. if FileManager.default.fileExists(atPath: certNamePath) {
  105. do {
  106. try FileManager.default.removeItem(atPath: certNamePath)
  107. } catch { }
  108. }
  109. let file = fopen(certNamePath, "w")
  110. if file != nil {
  111. PEM_write_X509(file, x509cert);
  112. }
  113. fclose(file);
  114. X509_free(x509cert);
  115. }
  116. }
  117. private func secTrustGetLeafCertificate(_ trust: SecTrust) -> SecCertificate? {
  118. let result: SecCertificate?
  119. if SecTrustGetCertificateCount(trust) > 0 {
  120. result = SecTrustGetCertificateAtIndex(trust, 0)!
  121. assert(result != nil);
  122. } else {
  123. result = nil
  124. }
  125. return result
  126. }
  127. @objc func convertFiles(_ files: [NCFile], urlString: String, serverUrl : String?, user: String) -> [tableMetadata] {
  128. var metadatas = [tableMetadata]()
  129. for file in files {
  130. if !CCUtility.getShowHiddenFiles() && file.fileName.first == "." { continue }
  131. if file.fileName.count == 0 { continue }
  132. let metadata = tableMetadata()
  133. metadata.account = account
  134. metadata.commentsUnread = file.commentsUnread
  135. metadata.contentType = file.contentType
  136. metadata.date = file.date
  137. metadata.directory = file.directory
  138. metadata.e2eEncrypted = file.e2eEncrypted
  139. metadata.etag = file.etag
  140. metadata.favorite = file.favorite
  141. metadata.fileId = file.fileId
  142. metadata.fileName = file.fileName
  143. metadata.fileNameView = file.fileName
  144. metadata.hasPreview = file.hasPreview
  145. metadata.mountType = file.mountType
  146. metadata.ocId = file.ocId
  147. metadata.ownerId = file.ownerId
  148. metadata.ownerDisplayName = file.ownerDisplayName
  149. metadata.permissions = file.permissions
  150. metadata.quotaUsedBytes = file.quotaUsedBytes
  151. metadata.quotaAvailableBytes = file.quotaAvailableBytes
  152. metadata.resourceType = file.resourceType
  153. if serverUrl == nil {
  154. metadata.serverUrl = urlString + file.path.replacingOccurrences(of: "/remote.php/dav/files/"+user, with: "").dropLast()
  155. } else {
  156. metadata.serverUrl = serverUrl!
  157. }
  158. metadata.size = file.size
  159. CCUtility.insertTypeFileIconName(file.fileName, metadata: metadata)
  160. metadatas.append(metadata)
  161. }
  162. return metadatas
  163. }
  164. }