AppDelegate.swift 18 KB

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