NCConfigServer.swift 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. //
  2. // NCConfigServer.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 05/12/22.
  6. // Copyright © 2022 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 Swifter
  25. import NextcloudKit
  26. // Source:
  27. // https://stackoverflow.com/questions/2338035/installing-a-configuration-profile-on-iphone-programmatically
  28. @objc class NCConfigServer: NSObject, UIActionSheetDelegate, URLSessionDelegate {
  29. // Start service
  30. @objc func startService(url: URL) {
  31. let defaultSessionConfiguration = URLSessionConfiguration.default
  32. let defaultSession = URLSession(configuration: defaultSessionConfiguration, delegate: self, delegateQueue: nil)
  33. var urlRequest = URLRequest(url: url)
  34. urlRequest.headers = NKCommon.shared.getStandardHeaders(nil, customUserAgent: nil)
  35. let dataTask = defaultSession.dataTask(with: urlRequest) { (data, response, error) in
  36. if let error = error {
  37. let error = NKError(errorCode: error._code, errorDescription: error.localizedDescription)
  38. NCContentPresenter.shared.showInfo(error: error)
  39. } else if let data = data {
  40. DispatchQueue.main.async { self.start(data: data) }
  41. }
  42. }
  43. dataTask.resume()
  44. }
  45. func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  46. DispatchQueue.global().async {
  47. NCNetworking.shared.checkTrustedChallenge(session, didReceive: challenge, completionHandler: completionHandler)
  48. }
  49. }
  50. private enum ConfigState: Int {
  51. case Stopped, Ready, InstalledConfig, BackToApp
  52. }
  53. internal let listeningPort: in_port_t = 8080
  54. internal var configName: String = "Profile install"
  55. private var localServer: HttpServer?
  56. private var returnURL: String = ""
  57. private var configData: Data?
  58. private var serverState: ConfigState = .Stopped
  59. private var registeredForNotifications = false
  60. private var backgroundTask = UIBackgroundTaskIdentifier.invalid
  61. deinit {
  62. unregisterFromNotifications()
  63. }
  64. // MARK: - Control functions
  65. internal func start(data: Data) {
  66. self.configData = data
  67. self.localServer = HttpServer()
  68. self.setupHandlers()
  69. let page = self.baseURL(pathComponent: "install/")
  70. let url = URL(string: page)!
  71. if UIApplication.shared.canOpenURL(url as URL) {
  72. do {
  73. try localServer?.start(listeningPort, forceIPv4: false, priority: .default)
  74. serverState = .Ready
  75. registerForNotifications()
  76. UIApplication.shared.open(url)
  77. } catch {
  78. let error = NKError(errorCode: error._code, errorDescription: error.localizedDescription)
  79. NCContentPresenter.shared.showInfo(error: error)
  80. self.stop()
  81. }
  82. }
  83. }
  84. internal func stop() {
  85. if serverState != .Stopped {
  86. serverState = .Stopped
  87. unregisterFromNotifications()
  88. }
  89. }
  90. // MARK: - Private functions
  91. private func setupHandlers() {
  92. localServer?["/install"] = { request in
  93. switch self.serverState {
  94. case .Stopped:
  95. return .notFound()
  96. case .Ready:
  97. self.serverState = .InstalledConfig
  98. return HttpResponse.raw(200, "OK", ["Content-Type": "application/x-apple-aspen-config"], { writer in
  99. do {
  100. if let configData = self.configData {
  101. try writer.write(configData)
  102. }
  103. } catch {
  104. print("Failed to write response data")
  105. }
  106. })
  107. case .InstalledConfig:
  108. return .movedPermanently(self.returnURL)
  109. case .BackToApp:
  110. let page = self.basePage(pathComponent: nil)
  111. return .ok(.html(page))
  112. }
  113. }
  114. }
  115. private func baseURL(pathComponent: String?) -> String {
  116. var page = "http://localhost:\(listeningPort)"
  117. if let component = pathComponent {
  118. page += "/\(component)"
  119. }
  120. return page
  121. }
  122. private func basePage(pathComponent: String?) -> String {
  123. var page = "<!doctype html><html>" + "<head><meta charset='utf-8'><title>\(self.configName)</title></head>"
  124. if let component = pathComponent {
  125. let script = "function load() { window.location.href='\(self.baseURL(pathComponent: component))'; } window.setInterval(load, 800);"
  126. page += "<script>\(script)</script>"
  127. }
  128. page += "<body></body></html>"
  129. return page
  130. }
  131. private func returnedToApp() {
  132. if serverState != .Stopped {
  133. serverState = .BackToApp
  134. localServer?.stop()
  135. }
  136. }
  137. private func registerForNotifications() {
  138. if !registeredForNotifications {
  139. let notificationCenter = NotificationCenter.default
  140. notificationCenter.addObserver(self, selector: #selector(didEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
  141. notificationCenter.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
  142. registeredForNotifications = true
  143. }
  144. }
  145. private func unregisterFromNotifications() {
  146. if registeredForNotifications {
  147. let notificationCenter = NotificationCenter.default
  148. notificationCenter.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil)
  149. notificationCenter.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil)
  150. registeredForNotifications = false
  151. }
  152. }
  153. @objc internal func didEnterBackground(notification: NSNotification) {
  154. if serverState != .Stopped {
  155. startBackgroundTask()
  156. }
  157. }
  158. @objc internal func willEnterForeground(notification: NSNotification) {
  159. if backgroundTask != UIBackgroundTaskIdentifier.invalid {
  160. stopBackgroundTask()
  161. returnedToApp()
  162. }
  163. }
  164. private func startBackgroundTask() {
  165. let application = UIApplication.shared
  166. backgroundTask = application.beginBackgroundTask(expirationHandler: {
  167. DispatchQueue.main.async {
  168. self.stopBackgroundTask()
  169. }
  170. })
  171. }
  172. private func stopBackgroundTask() {
  173. if backgroundTask != UIBackgroundTaskIdentifier.invalid {
  174. UIApplication.shared.endBackgroundTask(self.backgroundTask)
  175. backgroundTask = UIBackgroundTaskIdentifier.invalid
  176. }
  177. }
  178. }