AppDelegate.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. //
  2. // AppDelegate.swift
  3. // TunneledWebRequest
  4. //
  5. /*
  6. Licensed under Creative Commons Zero (CC0).
  7. https://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. import UIKit
  10. import PsiphonTunnel
  11. @UIApplicationMain
  12. class AppDelegate: UIResponder, UIApplicationDelegate {
  13. var window: UIWindow?
  14. // The instance of PsiphonTunnel we'll use for connecting.
  15. var psiphonTunnel: PsiphonTunnel?
  16. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  17. // Override point for customization after application launch.
  18. self.psiphonTunnel = PsiphonTunnel.newPsiphonTunnel(self)
  19. return true
  20. }
  21. func applicationWillResignActive(_ application: UIApplication) {
  22. // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
  23. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
  24. }
  25. func applicationDidEnterBackground(_ application: UIApplication) {
  26. // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
  27. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  28. }
  29. func applicationWillEnterForeground(_ application: UIApplication) {
  30. // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
  31. }
  32. func applicationDidBecomeActive(_ application: UIApplication) {
  33. // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
  34. DispatchQueue.global(qos: .default).async {
  35. // Start up the tunnel and begin connecting.
  36. // This could be started elsewhere or earlier.
  37. NSLog("Starting tunnel")
  38. guard let success = self.psiphonTunnel?.start(true), success else {
  39. NSLog("psiphonTunnel.start returned false")
  40. return
  41. }
  42. // The Psiphon Library exposes reachability functions, which can be used for detecting internet status.
  43. let reachability = Reachability.forInternetConnection()
  44. let networkStatus = reachability?.currentReachabilityStatus()
  45. NSLog("Internet is reachable? \(networkStatus != NotReachable)")
  46. }
  47. }
  48. func applicationWillTerminate(_ application: UIApplication) {
  49. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  50. // Clean up the tunnel
  51. NSLog("Stopping tunnel")
  52. self.psiphonTunnel?.stop()
  53. }
  54. /// Request URL using URLSession configured to use the current proxy.
  55. /// * parameters:
  56. /// - url: The URL to request.
  57. /// - completion: A callback function that will received the string obtained
  58. /// from the request, or nil if there's an error.
  59. /// * returns: The string obtained from the request, or nil if there's an error.
  60. func makeRequestViaUrlSessionProxy(_ url: String, completion: @escaping (_ result: String?) -> ()) {
  61. let socksProxyPort = self.psiphonTunnel!.getLocalSocksProxyPort()
  62. assert(socksProxyPort > 0)
  63. let request = URLRequest(url: URL(string: url)!)
  64. let config = URLSessionConfiguration.ephemeral
  65. config.requestCachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  66. config.connectionProxyDictionary = [AnyHashable: Any]()
  67. // Enable and set the SOCKS proxy values.
  68. config.connectionProxyDictionary?[kCFStreamPropertySOCKSProxy as String] = 1
  69. config.connectionProxyDictionary?[kCFStreamPropertySOCKSProxyHost as String] = "127.0.0.1"
  70. config.connectionProxyDictionary?[kCFStreamPropertySOCKSProxyPort as String] = socksProxyPort
  71. // Alternatively, the HTTP proxy can be used. Below are the settings for that.
  72. // The HTTPS key constants are mismatched and Xcode gives deprecation warnings, but they seem to be necessary to proxy HTTPS requests. This is probably a bug on Apple's side; see: https://forums.developer.apple.com/thread/19356#131446
  73. // config.connectionProxyDictionary?[kCFNetworkProxiesHTTPEnable as String] = 1
  74. // config.connectionProxyDictionary?[kCFNetworkProxiesHTTPProxy as String] = "127.0.0.1"
  75. // config.connectionProxyDictionary?[kCFNetworkProxiesHTTPPort as String] = self.httpProxyPort
  76. // config.connectionProxyDictionary?[kCFStreamPropertyHTTPSProxyHost as String] = "127.0.0.1"
  77. // config.connectionProxyDictionary?[kCFStreamPropertyHTTPSProxyPort as String] = self.httpProxyPort
  78. let session = URLSession.init(configuration: config, delegate: nil, delegateQueue: OperationQueue.current)
  79. // Create the URLSession task that will make the request via the tunnel proxy.
  80. let task = session.dataTask(with: request) {
  81. (data: Data?, response: URLResponse?, error: Error?) in
  82. if error != nil {
  83. NSLog("Client-side error in request to \(url): \(String(describing: error))")
  84. // Invoke the callback indicating error.
  85. completion(nil)
  86. return
  87. }
  88. if data == nil {
  89. NSLog("Data from request to \(url) is nil")
  90. // Invoke the callback indicating error.
  91. completion(nil)
  92. return
  93. }
  94. let httpResponse = response as? HTTPURLResponse
  95. if httpResponse?.statusCode != 200 {
  96. NSLog("Server-side error in request to \(url): \(String(describing: httpResponse))")
  97. // Invoke the callback indicating error.
  98. completion(nil)
  99. return
  100. }
  101. let encodingName = response?.textEncodingName != nil ? response?.textEncodingName : "utf-8"
  102. let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName as CFString!))
  103. let stringData = String(data: data!, encoding: String.Encoding(rawValue: UInt(encoding)))
  104. // Make sure the session is cleaned up.
  105. session.invalidateAndCancel()
  106. // Invoke the callback with the result.
  107. completion(stringData)
  108. }
  109. // Start the request task.
  110. task.resume()
  111. }
  112. /// Request URL using Psiphon's "URL proxy" mode.
  113. /// For details, see the comment near the top of:
  114. /// https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/master/psiphon/httpProxy.go
  115. /// * parameters:
  116. /// - url: The URL to request.
  117. /// - completion: A callback function that will received the string obtained
  118. /// from the request, or nil if there's an error.
  119. /// * returns: The string obtained from the request, or nil if there's an error.
  120. func makeRequestViaUrlProxy(_ url: String, completion: @escaping (_ result: String?) -> ()) {
  121. let httpProxyPort = self.psiphonTunnel!.getLocalHttpProxyPort()
  122. assert(httpProxyPort > 0)
  123. // The target URL must be encoded so as to be valid within a query parameter.
  124. // See this SO answer for why we're using this CharacterSet (and not using: https://stackoverflow.com/a/24888789
  125. let queryParamCharsAllowed = CharacterSet.init(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
  126. let encodedTargetURL = url.addingPercentEncoding(withAllowedCharacters: queryParamCharsAllowed)
  127. let proxiedURL = "http://127.0.0.1:\(httpProxyPort)/tunneled/\(encodedTargetURL!)"
  128. let task = URLSession.shared.dataTask(with: URL(string: proxiedURL)!) {
  129. (data: Data?, response: URLResponse?, error: Error?) in
  130. if error != nil {
  131. NSLog("Client-side error in request to \(url): \(String(describing: error))")
  132. // Invoke the callback indicating error.
  133. completion(nil)
  134. return
  135. }
  136. if data == nil {
  137. NSLog("Data from request to \(url) is nil")
  138. // Invoke the callback indicating error.
  139. completion(nil)
  140. return
  141. }
  142. let httpResponse = response as? HTTPURLResponse
  143. if httpResponse?.statusCode != 200 {
  144. NSLog("Server-side error in request to \(url): \(String(describing: httpResponse))")
  145. // Invoke the callback indicating error.
  146. completion(nil)
  147. return
  148. }
  149. let encodingName = response?.textEncodingName != nil ? response?.textEncodingName : "utf-8"
  150. let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName as CFString!))
  151. let stringData = String(data: data!, encoding: String.Encoding(rawValue: UInt(encoding)))
  152. // Invoke the callback with the result.
  153. completion(stringData)
  154. }
  155. // Start the request task.
  156. task.resume()
  157. }
  158. }
  159. // MARK: TunneledAppDelegate implementation
  160. // See the protocol definition for details about the methods.
  161. // Note that we're excluding all the optional methods that we aren't using,
  162. // however your needs may be different.
  163. extension AppDelegate: TunneledAppDelegate {
  164. func getPsiphonConfig() -> Any? {
  165. // In this example, we're going to retrieve our Psiphon config from a file in the app bundle.
  166. // Alternatively, it could be a string literal in the code, or whatever makes sense.
  167. guard let psiphonConfigUrl = Bundle.main.url(forResource: "psiphon-config", withExtension: "json") else {
  168. NSLog("Error getting Psiphon config resource file URL!")
  169. return nil
  170. }
  171. do {
  172. return try String.init(contentsOf: psiphonConfigUrl)
  173. } catch {
  174. NSLog("Error reading Psiphon config resource file!")
  175. return nil
  176. }
  177. }
  178. /// Read the Psiphon embedded server entries resource file and return the contents.
  179. /// * returns: The string of the contents of the file.
  180. func getEmbeddedServerEntries() -> String? {
  181. guard let psiphonEmbeddedServerEntriesUrl = Bundle.main.url(forResource: "psiphon-embedded-server-entries", withExtension: "txt") else {
  182. NSLog("Error getting Psiphon embedded server entries resource file URL!")
  183. return nil
  184. }
  185. do {
  186. return try String.init(contentsOf: psiphonEmbeddedServerEntriesUrl)
  187. } catch {
  188. NSLog("Error reading Psiphon embedded server entries resource file!")
  189. return nil
  190. }
  191. }
  192. func onDiagnosticMessage(_ message: String, withTimestamp timestamp: String) {
  193. NSLog("onDiagnosticMessage(%@): %@", timestamp, message)
  194. }
  195. func onConnected() {
  196. NSLog("onConnected")
  197. // After we're connected, make tunneled requests and populate the webview.
  198. DispatchQueue.global(qos: .default).async {
  199. // First we'll make a "what is my IP" request via makeRequestViaUrlSessionProxy().
  200. let url = "https://freegeoip.app/json/"
  201. self.makeRequestViaUrlSessionProxy(url) {
  202. (_ result: String?) in
  203. if result == nil {
  204. NSLog("Failed to get \(url)")
  205. return
  206. }
  207. // Do a little pretty-printing.
  208. let prettyResult = result?.replacingOccurrences(of: ",", with: ",\n ")
  209. .replacingOccurrences(of: "{", with: "{\n ")
  210. .replacingOccurrences(of: "}", with: "\n}")
  211. DispatchQueue.main.sync {
  212. // Load the result into the view.
  213. let mainView = self.window?.rootViewController as! ViewController
  214. mainView.appendToView("Result from \(url):\n\(prettyResult!)")
  215. }
  216. // Then we'll make a different "what is my IP" request via makeRequestViaUrlProxy().
  217. DispatchQueue.global(qos: .default).async {
  218. let url = "https://ifconfig.co/json"
  219. self.makeRequestViaUrlProxy(url) {
  220. (_ result: String?) in
  221. if result == nil {
  222. NSLog("Failed to get \(url)")
  223. return
  224. }
  225. // Do a little pretty-printing.
  226. let prettyResult = result?.replacingOccurrences(of: ",", with: ",\n ")
  227. .replacingOccurrences(of: "{", with: "{\n ")
  228. .replacingOccurrences(of: "}", with: "\n}")
  229. DispatchQueue.main.sync {
  230. // Load the result into the view.
  231. let mainView = self.window?.rootViewController as! ViewController
  232. mainView.appendToView("Result from \(url):\n\(prettyResult!)")
  233. }
  234. // We'll leave the tunnel open for when we want to make
  235. // more requests. It will get stopped by `applicationWillTerminate`.
  236. }
  237. }
  238. }
  239. }
  240. }
  241. }