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