NCConfigServer.swift 7.2 KB

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