NCConfigServer.swift 7.2 KB

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