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