AppDelegate.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. @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. @objc public 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. internal func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  30. // Override point for customization after application launch.
  31. self.psiphonTunnel = PsiphonTunnel.newPsiphonTunnel(self)
  32. return true
  33. }
  34. func applicationWillResignActive(_ application: UIApplication) {
  35. // 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.
  36. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
  37. }
  38. func applicationDidEnterBackground(_ application: UIApplication) {
  39. // 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.
  40. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  41. }
  42. func applicationWillEnterForeground(_ application: UIApplication) {
  43. // 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.
  44. }
  45. func applicationDidBecomeActive(_ application: UIApplication) {
  46. // 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.
  47. DispatchQueue.global(qos: .default).async {
  48. // Start up the tunnel and begin connecting.
  49. // This could be started elsewhere or earlier.
  50. NSLog("Starting tunnel")
  51. guard let success = self.psiphonTunnel?.start(true), success else {
  52. NSLog("psiphonTunnel.start returned false")
  53. return
  54. }
  55. // The Psiphon Library exposes reachability functions, which can be used for detecting internet status.
  56. let reachability = Reachability.forInternetConnection()
  57. let networkStatus = reachability?.currentReachabilityStatus()
  58. NSLog("Internet is reachable? \(networkStatus != NotReachable)")
  59. }
  60. }
  61. func applicationWillTerminate(_ application: UIApplication) {
  62. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  63. // Clean up the tunnel
  64. NSLog("Stopping tunnel")
  65. self.psiphonTunnel?.stop()
  66. }
  67. /// Request URL using URLSession configured to use the current proxy.
  68. /// * parameters:
  69. /// - url: The URL to request.
  70. /// - completion: A callback function that will received the string obtained
  71. /// from the request, or nil if there's an error.
  72. /// * returns: The string obtained from the request, or nil if there's an error.
  73. func makeRequestViaUrlSessionProxy(_ url: String, completion: @escaping (_ result: String?, _ error: String?) -> ()) {
  74. let socksProxyPort = self.socksProxyPort
  75. assert(socksProxyPort > 0)
  76. let request = URLRequest(url: URL(string: url)!)
  77. let config = URLSessionConfiguration.ephemeral
  78. config.requestCachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  79. config.connectionProxyDictionary = [AnyHashable: Any]()
  80. config.timeoutIntervalForRequest = 60 * 5
  81. // Enable and set the SOCKS proxy values.
  82. config.connectionProxyDictionary?[kCFStreamPropertySOCKSProxy as String] = 1
  83. config.connectionProxyDictionary?[kCFStreamPropertySOCKSProxyHost as String] = "127.0.0.1"
  84. config.connectionProxyDictionary?[kCFStreamPropertySOCKSProxyPort as String] = socksProxyPort
  85. // Alternatively, the HTTP proxy can be used. Below are the settings for that.
  86. // 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
  87. // config.connectionProxyDictionary?[kCFNetworkProxiesHTTPEnable as String] = 1
  88. // config.connectionProxyDictionary?[kCFNetworkProxiesHTTPProxy as String] = "127.0.0.1"
  89. // config.connectionProxyDictionary?[kCFNetworkProxiesHTTPPort as String] = self.httpProxyPort
  90. // config.connectionProxyDictionary?[kCFStreamPropertyHTTPSProxyHost as String] = "127.0.0.1"
  91. // config.connectionProxyDictionary?[kCFStreamPropertyHTTPSProxyPort as String] = self.httpProxyPort
  92. let session = URLSession.init(configuration: config)
  93. // Create the URLSession task that will make the request via the tunnel proxy.
  94. let task = session.dataTask(with: request) {
  95. (data: Data?, response: URLResponse?, error: Error?) in
  96. if error != nil {
  97. let errorString = "Client-side error in request to \(url): \(String(describing: error))"
  98. NSLog(errorString)
  99. // Invoke the callback indicating error.
  100. completion(nil, errorString)
  101. return
  102. }
  103. if data == nil {
  104. let errorString = "Data from request to \(url) is nil"
  105. NSLog(errorString)
  106. // Invoke the callback indicating error.
  107. completion(nil, errorString)
  108. return
  109. }
  110. let httpResponse = response as? HTTPURLResponse
  111. if httpResponse?.statusCode != 200 {
  112. let errorString = "Server-side error in request to \(url): \(String(describing: httpResponse))"
  113. NSLog(errorString)
  114. // Invoke the callback indicating error.
  115. completion(nil, errorString)
  116. return
  117. }
  118. let encodingName = response?.textEncodingName != nil ? response?.textEncodingName : "utf-8"
  119. let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName as CFString?))
  120. let stringData = String(data: data!, encoding: String.Encoding(rawValue: UInt(encoding)))
  121. // Make sure the session is cleaned up.
  122. session.invalidateAndCancel()
  123. // Invoke the callback with the result.
  124. completion(stringData, nil)
  125. }
  126. // Start the request task.
  127. task.resume()
  128. }
  129. /// Request URL using Psiphon's "URL proxy" mode.
  130. /// For details, see the comment near the top of:
  131. /// https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/master/psiphon/httpProxy.go
  132. /// * parameters:
  133. /// - url: The URL to request.
  134. /// - completion: A callback function that will received the string obtained
  135. /// from the request, or nil if there's an error.
  136. /// * returns: The string obtained from the request, or nil if there's an error.
  137. func makeRequestViaUrlProxy(_ url: String, completion: @escaping (_ result: String?, _ error: String?) -> ()) {
  138. let httpProxyPort = self.httpProxyPort
  139. assert(httpProxyPort > 0)
  140. // The target URL must be encoded so as to be valid within a query parameter.
  141. // See this SO answer for why we're using this CharacterSet (and not using: https://stackoverflow.com/a/24888789
  142. let queryParamCharsAllowed = CharacterSet.init(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
  143. let encodedTargetURL = url.addingPercentEncoding(withAllowedCharacters: queryParamCharsAllowed)
  144. let proxiedURL = "http://127.0.0.1:\(httpProxyPort)/tunneled/\(encodedTargetURL!)"
  145. let task = URLSession.shared.dataTask(with: URL(string: proxiedURL)!) {
  146. (data: Data?, response: URLResponse?, error: Error?) in
  147. if error != nil {
  148. let errorString = "Client-side error in request to \(url): \(String(describing: error))"
  149. NSLog(errorString)
  150. // Invoke the callback indicating error.
  151. completion(nil, errorString)
  152. return
  153. }
  154. if data == nil {
  155. let errorString = "Data from request to \(url) is nil"
  156. NSLog(errorString)
  157. // Invoke the callback indicating error.
  158. completion(nil, errorString)
  159. return
  160. }
  161. let httpResponse = response as? HTTPURLResponse
  162. if httpResponse?.statusCode != 200 {
  163. let errorString = "Server-side error in request to \(url): \(String(describing: httpResponse))"
  164. NSLog(errorString)
  165. // Invoke the callback indicating error.
  166. completion(nil, errorString)
  167. return
  168. }
  169. let encodingName = response?.textEncodingName != nil ? response?.textEncodingName : "utf-8"
  170. let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName as CFString?))
  171. let stringData = String(data: data!, encoding: String.Encoding(rawValue: UInt(encoding)))
  172. // Invoke the callback with the result.
  173. completion(stringData, nil)
  174. }
  175. // Start the request task.
  176. task.resume()
  177. }
  178. }
  179. // MARK: TunneledAppDelegate implementation
  180. // See the protocol definition for details about the methods.
  181. // Note that we're excluding all the optional methods that we aren't using,
  182. // however your needs may be different.
  183. extension AppDelegate: TunneledAppDelegate {
  184. func getPsiphonConfig() -> Any? {
  185. // In this example, we're going to retrieve our Psiphon config from a file in the app bundle.
  186. // Alternatively, it could be a string literal in the code, or whatever makes sense.
  187. guard let psiphonConfigUrl = Bundle.main.url(forResource: "psiphon-config", withExtension: "json") else {
  188. NSLog("Error getting Psiphon config resource file URL!")
  189. return nil
  190. }
  191. do {
  192. return try String.init(contentsOf: psiphonConfigUrl)
  193. } catch {
  194. NSLog("Error reading Psiphon config resource file!")
  195. return nil
  196. }
  197. }
  198. /// Read the Psiphon embedded server entries resource file and return the contents.
  199. /// * returns: The string of the contents of the file.
  200. func getEmbeddedServerEntries() -> String? {
  201. guard let psiphonEmbeddedServerEntriesUrl = Bundle.main.url(forResource: "psiphon-embedded-server-entries", withExtension: "txt") else {
  202. NSLog("Error getting Psiphon embedded server entries resource file URL!")
  203. return nil
  204. }
  205. do {
  206. return try String.init(contentsOf: psiphonEmbeddedServerEntriesUrl)
  207. } catch {
  208. NSLog("Error reading Psiphon embedded server entries resource file!")
  209. return nil
  210. }
  211. }
  212. func onDiagnosticMessage(_ message: String, withTimestamp timestamp: String) {
  213. NSLog("onDiagnosticMessage(%@): %@", timestamp, message)
  214. }
  215. func onConnected() {
  216. NSLog("onConnected")
  217. // After we're connected, make tunneled requests and populate the webview.
  218. DispatchQueue.global(qos: .default).async {
  219. // First we'll make a "what is my IP" request via makeRequestViaUrlSessionProxy().
  220. let url = "https://freegeoip.app/json/"
  221. self.makeRequestViaUrlSessionProxy(url) {
  222. (_ result: String?, _ error: String?) in
  223. if let errorString = error?.replacingOccurrences(of: ",", with: ",\n ")
  224. .replacingOccurrences(of: "{", with: "{\n ")
  225. .replacingOccurrences(of: "}", with: "\n}")
  226. {
  227. DispatchQueue.main.sync {
  228. // Load the result into the view.
  229. let mainView = self.window?.rootViewController as! ViewController
  230. mainView.appendToView("""
  231. Error from \(url):\n\n
  232. \(errorString)\n\n
  233. Using makeRequestViaUrlSessionProxy.\n\n
  234. Check logs for error.
  235. """)
  236. }
  237. } else {
  238. if result == nil {
  239. NSLog("Failed to get \(url)")
  240. return
  241. }
  242. // Do a little pretty-printing.
  243. let prettyResult = result?.replacingOccurrences(of: ",", with: ",\n ")
  244. .replacingOccurrences(of: "{", with: "{\n ")
  245. .replacingOccurrences(of: "}", with: "\n}")
  246. DispatchQueue.main.sync {
  247. // Load the result into the view.
  248. let mainView = self.window?.rootViewController as! ViewController
  249. mainView.appendToView("Result from \(url):\n\(prettyResult!)")
  250. }
  251. }
  252. // Then we'll make a different "what is my IP" request via makeRequestViaUrlProxy().
  253. DispatchQueue.global(qos: .default).async {
  254. let url = "https://ifconfig.co/json"
  255. self.makeRequestViaUrlProxy(url) {
  256. (_ result: String?, _ error: String?) in
  257. if let errorString = error?.replacingOccurrences(of: ",", with: ",\n ")
  258. .replacingOccurrences(of: "{", with: "{\n ")
  259. .replacingOccurrences(of: "}", with: "\n}")
  260. {
  261. DispatchQueue.main.sync {
  262. // Load the result into the view.
  263. let mainView = self.window?.rootViewController as! ViewController
  264. mainView.appendToView("""
  265. Error from \(url):\n\n
  266. \(errorString)\n\n
  267. Using makeRequestViaUrlProxy.\n\n
  268. Check logs for error.
  269. """)
  270. }
  271. return
  272. } else {
  273. if result == nil {
  274. NSLog("Failed to get \(url)")
  275. return
  276. }
  277. // Do a little pretty-printing.
  278. let prettyResult = result?.replacingOccurrences(of: ",", with: ",\n ")
  279. .replacingOccurrences(of: "{", with: "{\n ")
  280. .replacingOccurrences(of: "}", with: "\n}")
  281. DispatchQueue.main.sync {
  282. // Load the result into the view.
  283. let mainView = self.window?.rootViewController as! ViewController
  284. mainView.appendToView("Result from \(url):\n\(prettyResult!)")
  285. }
  286. }
  287. // We'll leave the tunnel open for when we want to make
  288. // more requests. It will get stopped by `applicationWillTerminate`.
  289. }
  290. }
  291. }
  292. }
  293. }
  294. func onListeningSocksProxyPort(_ port: Int) {
  295. DispatchQueue.main.async {
  296. self.socksProxyPort = port
  297. }
  298. }
  299. func onListeningHttpProxyPort(_ port: Int) {
  300. DispatchQueue.main.async {
  301. self.httpProxyPort = port
  302. }
  303. }
  304. func onConnectedServerRegion(_ region: String) {
  305. NSLog("onConnectedServerRegion(%@)", region)
  306. }
  307. }