AppDelegate.swift 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. //
  2. // AppDelegate.swift
  3. // TunneledWebView
  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. import Network
  12. enum ProxyType {
  13. case http
  14. case socks
  15. }
  16. struct Proxy {
  17. var host: NWEndpoint.Host
  18. var type: ProxyType
  19. }
  20. @UIApplicationMain
  21. @objc class AppDelegate: UIResponder, UIApplicationDelegate {
  22. var window: UIWindow?
  23. var proxy: Proxy?
  24. // The instance of PsiphonTunnel we'll use for connecting.
  25. var psiphonTunnel: PsiphonTunnel?
  26. @objc public class func sharedDelegate() -> AppDelegate {
  27. var delegate: AppDelegate?
  28. if (Thread.isMainThread) {
  29. delegate = UIApplication.shared.delegate as? AppDelegate
  30. } else {
  31. DispatchQueue.main.sync {
  32. delegate = UIApplication.shared.delegate as? AppDelegate
  33. }
  34. }
  35. return delegate!
  36. }
  37. internal func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  38. // Override point for customization after application launch.
  39. self.psiphonTunnel = PsiphonTunnel.newPsiphonTunnel(self)
  40. // Choose which proxy to use. Callback from PsiphonTunnel will determine the proxy port.
  41. // If not set, then WKWebView requests are not proxied.
  42. self.proxy = Proxy(host: "127.0.0.1", type: .http)
  43. return true
  44. }
  45. func applicationWillResignActive(_ application: UIApplication) {
  46. // 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.
  47. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
  48. }
  49. func applicationDidEnterBackground(_ application: UIApplication) {
  50. // 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.
  51. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  52. }
  53. func applicationWillEnterForeground(_ application: UIApplication) {
  54. // 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.
  55. }
  56. func applicationDidBecomeActive(_ application: UIApplication) {
  57. // 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.
  58. DispatchQueue.global(qos: .default).async {
  59. // Start up the tunnel and begin connecting.
  60. // This could be started elsewhere or earlier.
  61. NSLog("Starting tunnel")
  62. guard let success = self.psiphonTunnel?.start(true), success else {
  63. NSLog("psiphonTunnel.start returned false")
  64. return
  65. }
  66. // The Psiphon Library exposes reachability functions, which can be used for detecting internet status.
  67. let reachability = Reachability.forInternetConnection()
  68. let networkStatus = reachability?.currentReachabilityStatus()
  69. NSLog("Internet is reachable? \(networkStatus != NotReachable)")
  70. }
  71. }
  72. func applicationWillTerminate(_ application: UIApplication) {
  73. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  74. // Clean up the tunnel
  75. NSLog("Stopping tunnel")
  76. self.psiphonTunnel?.stop()
  77. }
  78. }
  79. // MARK: TunneledAppDelegate implementation
  80. // See the protocol definition for details about the methods.
  81. // Note that we're excluding all the optional methods that we aren't using,
  82. // however your needs may be different.
  83. extension AppDelegate: TunneledAppDelegate {
  84. func getPsiphonConfig() -> Any? {
  85. // In this example, we're going to retrieve our Psiphon config from a file in the app bundle.
  86. // Alternatively, it could be a string literal in the code, or whatever makes sense.
  87. guard let psiphonConfigUrl = Bundle.main.url(forResource: "psiphon-config", withExtension: "json") else {
  88. NSLog("Error getting Psiphon config resource file URL!")
  89. return nil
  90. }
  91. do {
  92. return try String.init(contentsOf: psiphonConfigUrl)
  93. } catch {
  94. NSLog("Error reading Psiphon config resource file!")
  95. return nil
  96. }
  97. }
  98. /// Read the Psiphon embedded server entries resource file and return the contents.
  99. /// * returns: The string of the contents of the file.
  100. func getEmbeddedServerEntries() -> String? {
  101. guard let psiphonEmbeddedServerEntriesUrl = Bundle.main.url(forResource: "psiphon-embedded-server-entries", withExtension: "txt") else {
  102. NSLog("Error getting Psiphon embedded server entries resource file URL!")
  103. return nil
  104. }
  105. do {
  106. return try String.init(contentsOf: psiphonEmbeddedServerEntriesUrl)
  107. } catch {
  108. NSLog("Error reading Psiphon embedded server entries resource file!")
  109. return nil
  110. }
  111. }
  112. func onDiagnosticMessage(_ message: String, withTimestamp timestamp: String) {
  113. NSLog("onDiagnosticMessage(%@): %@", timestamp, message)
  114. }
  115. func onConnected() {
  116. NSLog("onConnected")
  117. DispatchQueue.main.sync {
  118. let urlString = "https://freegeoip.app/"
  119. let url = URL.init(string: urlString)!
  120. let mainView = self.window?.rootViewController as! ViewController
  121. mainView.loadUrl(url)
  122. }
  123. }
  124. func onListeningSocksProxyPort(_ port: Int) {
  125. NSLog("onListeningSocksProxyPort: %d", port)
  126. if case.socks = self.proxy?.type {
  127. NSLog("Configuring WKWebView to use SOCKS proxy %@:%d", self.proxy!.host.debugDescription, port)
  128. DispatchQueue.main.async {
  129. let endpoint = NWEndpoint.hostPort(
  130. host: self.proxy!.host,
  131. port: NWEndpoint.Port(rawValue:UInt16(port))!)
  132. let proxyConfig = ProxyConfiguration(socksv5Proxy: endpoint)
  133. let mainView = self.window?.rootViewController as! ViewController
  134. mainView.useProxyConfiguration(proxyConfig)
  135. }
  136. }
  137. }
  138. func onListeningHttpProxyPort(_ port: Int) {
  139. NSLog("onListeningHttpProxyPort: %d", port)
  140. if case.http = self.proxy?.type {
  141. NSLog("Configuring WKWebView to use HTTP proxy %@:%d", self.proxy!.host.debugDescription, port)
  142. DispatchQueue.main.async {
  143. let endpoint = NWEndpoint.hostPort(
  144. host: self.proxy!.host,
  145. port: NWEndpoint.Port(rawValue:UInt16(port))!)
  146. let proxyConfig = ProxyConfiguration(httpCONNECTProxy: endpoint)
  147. let mainView = self.window?.rootViewController as! ViewController
  148. mainView.useProxyConfiguration(proxyConfig)
  149. }
  150. }
  151. }
  152. }