AppDelegate.swift 7.5 KB

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