AppDelegate.swift 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. @UIApplicationMain
  12. @objc class AppDelegate: UIResponder, UIApplicationDelegate {
  13. var window: UIWindow?
  14. @objc public var socksProxyPort: Int = 0
  15. @objc public var httpProxyPort: Int = 0
  16. // The instance of PsiphonTunnel we'll use for connecting.
  17. var psiphonTunnel: PsiphonTunnel?
  18. // OCSP cache for making OCSP requests in certificate revocation checking
  19. var ocspCache: OCSPCache = OCSPCache.init(logger: {print("[OCSPCache]:", $0)})
  20. // Delegate for handling certificate validation.
  21. @objc public lazy var authURLSessionDelegate: OCSPAuthURLSessionDelegate =
  22. OCSPAuthURLSessionDelegate.init(logger: {print("[AuthURLSessionTaskDelegate]:", $0)},
  23. ocspCache: self.ocspCache,
  24. modifyOCSPURL:{
  25. assert(self.httpProxyPort > 0)
  26. let encodedTargetURL = URLEncode.encode($0.absoluteString)
  27. let proxiedURLString = "http://127.0.0.1:\(self.httpProxyPort)/tunneled/\(encodedTargetURL!)"
  28. let proxiedURL = URL.init(string: proxiedURLString)
  29. print("[OCSP] Updated OCSP URL \($0) to \(proxiedURL!)")
  30. return proxiedURL!},
  31. sessionConfig:nil)
  32. @objc public class func sharedDelegate() -> AppDelegate {
  33. var delegate: AppDelegate?
  34. if (Thread.isMainThread) {
  35. delegate = UIApplication.shared.delegate as? AppDelegate
  36. } else {
  37. DispatchQueue.main.sync {
  38. delegate = UIApplication.shared.delegate as? AppDelegate
  39. }
  40. }
  41. return delegate!
  42. }
  43. internal func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  44. // Override point for customization after application launch.
  45. // Set the class delegate and register NSURL subclass
  46. // JAHPAuthenticatingHTTPProtocol with NSURLProtocol.
  47. // See comments for `setDelegate` and `start` in
  48. // JAHPAuthenticatingHTTPProtocol.h
  49. /*******************************************************/
  50. /***** *****/
  51. /***** !!! WARNING !!! *****/
  52. /***** *****/
  53. /*******************************************************/
  54. /***** *****/
  55. /***** This methood of proxying UIWebView is not *****/
  56. /***** officially supported and requires extra *****/
  57. /***** steps to proxy audio / video content. *****/
  58. /***** Otherwise audio / video fetching may be *****/
  59. /***** untunneled! *****/
  60. /***** *****/
  61. /***** It is strongly advised that you read the *****/
  62. /***** "Caveats" section of README.md before *****/
  63. /***** using PsiphonTunnel to proxy UIWebView *****/
  64. /***** traffic. *****/
  65. /***** *****/
  66. /*******************************************************/
  67. JAHPAuthenticatingHTTPProtocol.setDelegate(self)
  68. JAHPAuthenticatingHTTPProtocol.start()
  69. self.psiphonTunnel = PsiphonTunnel.newPsiphonTunnel(self)
  70. return true
  71. }
  72. func applicationWillResignActive(_ application: UIApplication) {
  73. // 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.
  74. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
  75. }
  76. func applicationDidEnterBackground(_ application: UIApplication) {
  77. // 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.
  78. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  79. }
  80. func applicationWillEnterForeground(_ application: UIApplication) {
  81. // 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.
  82. }
  83. func applicationDidBecomeActive(_ application: UIApplication) {
  84. // 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.
  85. DispatchQueue.global(qos: .default).async {
  86. // Start up the tunnel and begin connecting.
  87. // This could be started elsewhere or earlier.
  88. NSLog("Starting tunnel")
  89. guard let success = self.psiphonTunnel?.start(true), success else {
  90. NSLog("psiphonTunnel.start returned false")
  91. return
  92. }
  93. // The Psiphon Library exposes reachability functions, which can be used for detecting internet status.
  94. let reachability = Reachability.forInternetConnection()
  95. let networkStatus = reachability?.currentReachabilityStatus()
  96. NSLog("Internet is reachable? \(networkStatus != NotReachable)")
  97. }
  98. }
  99. func applicationWillTerminate(_ application: UIApplication) {
  100. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  101. // Clean up the tunnel
  102. NSLog("Stopping tunnel")
  103. self.psiphonTunnel?.stop()
  104. }
  105. }
  106. extension AppDelegate: JAHPAuthenticatingHTTPProtocolDelegate {
  107. func authenticatingHTTPProtocol(_ authenticatingHTTPProtocol: JAHPAuthenticatingHTTPProtocol?, logMessage message: String) {
  108. NSLog("[JAHPAuthenticatingHTTPProtocol] %@", message)
  109. }
  110. }
  111. // MARK: TunneledAppDelegate implementation
  112. // See the protocol definition for details about the methods.
  113. // Note that we're excluding all the optional methods that we aren't using,
  114. // however your needs may be different.
  115. extension AppDelegate: TunneledAppDelegate {
  116. func getPsiphonConfig() -> Any? {
  117. // In this example, we're going to retrieve our Psiphon config from a file in the app bundle.
  118. // Alternatively, it could be a string literal in the code, or whatever makes sense.
  119. guard let psiphonConfigUrl = Bundle.main.url(forResource: "psiphon-config", withExtension: "json") else {
  120. NSLog("Error getting Psiphon config resource file URL!")
  121. return nil
  122. }
  123. do {
  124. return try String.init(contentsOf: psiphonConfigUrl)
  125. } catch {
  126. NSLog("Error reading Psiphon config resource file!")
  127. return nil
  128. }
  129. }
  130. /// Read the Psiphon embedded server entries resource file and return the contents.
  131. /// * returns: The string of the contents of the file.
  132. func getEmbeddedServerEntries() -> String? {
  133. guard let psiphonEmbeddedServerEntriesUrl = Bundle.main.url(forResource: "psiphon-embedded-server-entries", withExtension: "txt") else {
  134. NSLog("Error getting Psiphon embedded server entries resource file URL!")
  135. return nil
  136. }
  137. do {
  138. return try String.init(contentsOf: psiphonEmbeddedServerEntriesUrl)
  139. } catch {
  140. NSLog("Error reading Psiphon embedded server entries resource file!")
  141. return nil
  142. }
  143. }
  144. func onDiagnosticMessage(_ message: String, withTimestamp timestamp: String) {
  145. NSLog("onDiagnosticMessage(%@): %@", timestamp, message)
  146. }
  147. func onConnected() {
  148. NSLog("onConnected")
  149. DispatchQueue.main.sync {
  150. let urlString = "https://freegeoip.app/"
  151. let url = URL.init(string: urlString)!
  152. let mainView = self.window?.rootViewController as! ViewController
  153. mainView.loadUrl(url)
  154. }
  155. }
  156. func onListeningSocksProxyPort(_ port: Int) {
  157. DispatchQueue.main.async {
  158. JAHPAuthenticatingHTTPProtocol.resetSharedDemux()
  159. self.socksProxyPort = port
  160. }
  161. }
  162. func onListeningHttpProxyPort(_ port: Int) {
  163. DispatchQueue.main.async {
  164. JAHPAuthenticatingHTTPProtocol.resetSharedDemux()
  165. self.httpProxyPort = port
  166. }
  167. }
  168. }