PsiphonTunnel.java 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package ca.psiphon;
  20. import android.annotation.TargetApi;
  21. import android.content.Context;
  22. import android.net.ConnectivityManager;
  23. import android.net.LinkProperties;
  24. import android.net.Network;
  25. import android.net.NetworkCapabilities;
  26. import android.net.NetworkInfo;
  27. import android.net.NetworkRequest;
  28. import android.net.VpnService;
  29. import android.net.wifi.WifiInfo;
  30. import android.net.wifi.WifiManager;
  31. import android.os.Build;
  32. import android.os.ParcelFileDescriptor;
  33. import android.telephony.TelephonyManager;
  34. import android.text.TextUtils;
  35. import android.util.Base64;
  36. import org.json.JSONArray;
  37. import org.json.JSONException;
  38. import org.json.JSONObject;
  39. import java.io.File;
  40. import java.io.FileInputStream;
  41. import java.io.FileOutputStream;
  42. import java.io.IOException;
  43. import java.io.PrintStream;
  44. import java.lang.reflect.InvocationTargetException;
  45. import java.lang.reflect.Method;
  46. import java.net.Inet4Address;
  47. import java.net.Inet6Address;
  48. import java.net.InetAddress;
  49. import java.net.NetworkInterface;
  50. import java.net.SocketException;
  51. import java.security.KeyStore;
  52. import java.security.KeyStoreException;
  53. import java.security.NoSuchAlgorithmException;
  54. import java.security.cert.CertificateException;
  55. import java.security.cert.X509Certificate;
  56. import java.util.ArrayList;
  57. import java.util.Collection;
  58. import java.util.Collections;
  59. import java.util.Enumeration;
  60. import java.util.HashMap;
  61. import java.util.List;
  62. import java.util.Locale;
  63. import java.util.Map;
  64. import java.util.concurrent.CountDownLatch;
  65. import java.util.concurrent.atomic.AtomicBoolean;
  66. import java.util.concurrent.atomic.AtomicInteger;
  67. import java.util.concurrent.atomic.AtomicReference;
  68. import java.util.concurrent.Executors;
  69. import java.util.concurrent.ExecutorService;
  70. import java.util.concurrent.Future;
  71. import java.util.concurrent.TimeUnit;
  72. import psi.Psi;
  73. import psi.PsiphonProvider;
  74. import psi.PsiphonProviderNetwork;
  75. import psi.PsiphonProviderNoticeHandler;
  76. import psi.PsiphonProviderFeedbackHandler;
  77. public class PsiphonTunnel {
  78. public interface HostLogger {
  79. default public void onDiagnosticMessage(String message) {}
  80. }
  81. // Protocol used to communicate the outcome of feedback upload operations to the application
  82. // using PsiphonTunnelFeedback.
  83. public interface HostFeedbackHandler {
  84. // Callback which is invoked once the feedback upload has completed.
  85. // If the exception is non-null, then the upload failed.
  86. default public void sendFeedbackCompleted(java.lang.Exception e) {}
  87. }
  88. public interface HostLibraryLoader {
  89. default public void loadLibrary(String library) {
  90. System.loadLibrary(library);
  91. }
  92. }
  93. public interface HostService extends HostLogger, HostLibraryLoader {
  94. public String getAppName();
  95. public Context getContext();
  96. public String getPsiphonConfig();
  97. default public Object getVpnService() {return null;} // Object must be a VpnService (Android < 4 cannot reference this class name)
  98. default public Object newVpnServiceBuilder() {return null;} // Object must be a VpnService.Builder (Android < 4 cannot reference this class name)
  99. default public void onAvailableEgressRegions(List<String> regions) {}
  100. default public void onSocksProxyPortInUse(int port) {}
  101. default public void onHttpProxyPortInUse(int port) {}
  102. default public void onListeningSocksProxyPort(int port) {}
  103. default public void onListeningHttpProxyPort(int port) {}
  104. default public void onUpstreamProxyError(String message) {}
  105. default public void onConnecting() {}
  106. default public void onConnected() {}
  107. default public void onHomepage(String url) {}
  108. default public void onClientRegion(String region) {}
  109. default public void onClientAddress(String address) {}
  110. default public void onClientUpgradeDownloaded(String filename) {}
  111. default public void onClientIsLatestVersion() {}
  112. default public void onSplitTunnelRegions(List<String> regions) {}
  113. default public void onUntunneledAddress(String address) {}
  114. default public void onBytesTransferred(long sent, long received) {}
  115. default public void onStartedWaitingForNetworkConnectivity() {}
  116. default public void onStoppedWaitingForNetworkConnectivity() {}
  117. default public void onActiveAuthorizationIDs(List<String> authorizations) {}
  118. default public void onTrafficRateLimits(long upstreamBytesPerSecond, long downstreamBytesPerSecond) {}
  119. default public void onApplicationParameters(Object parameters) {}
  120. default public void onServerAlert(String reason, String subject, List<String> actionURLs) {}
  121. default public void onExiting() {}
  122. }
  123. private final HostService mHostService;
  124. private AtomicBoolean mVpnMode;
  125. private PrivateAddress mPrivateAddress;
  126. private AtomicReference<ParcelFileDescriptor> mTunFd;
  127. private AtomicInteger mLocalSocksProxyPort;
  128. private AtomicBoolean mRoutingThroughTunnel;
  129. private Thread mTun2SocksThread;
  130. private AtomicBoolean mIsWaitingForNetworkConnectivity;
  131. private AtomicReference<String> mClientPlatformPrefix;
  132. private AtomicReference<String> mClientPlatformSuffix;
  133. private final boolean mShouldRouteThroughTunnelAutomatically;
  134. private final NetworkMonitor mNetworkMonitor;
  135. private AtomicReference<String> mActiveNetworkType;
  136. private AtomicReference<String> mActiveNetworkDNSServers;
  137. // Only one PsiphonVpn instance may exist at a time, as the underlying
  138. // psi.Psi and tun2socks implementations each contain global state.
  139. private static PsiphonTunnel mPsiphonTunnel;
  140. public static synchronized PsiphonTunnel newPsiphonTunnel(HostService hostService) {
  141. return newPsiphonTunnelImpl(hostService, true);
  142. }
  143. // The two argument override in case the host app wants to take control over calling routeThroughTunnel()
  144. public static synchronized PsiphonTunnel newPsiphonTunnel(HostService hostService, boolean shouldRouteThroughTunnelAutomatically) {
  145. return newPsiphonTunnelImpl(hostService, shouldRouteThroughTunnelAutomatically);
  146. }
  147. private static PsiphonTunnel newPsiphonTunnelImpl(HostService hostService, boolean shouldRouteThroughTunnelAutomatically) {
  148. if (mPsiphonTunnel != null) {
  149. mPsiphonTunnel.stop();
  150. }
  151. // Load the native go code embedded in psi.aar
  152. hostService.loadLibrary("gojni");
  153. mPsiphonTunnel = new PsiphonTunnel(hostService, shouldRouteThroughTunnelAutomatically);
  154. return mPsiphonTunnel;
  155. }
  156. // Returns default path where upgrade downloads will be paved. Only applicable if
  157. // DataRootDirectory was not set in the outer config. If DataRootDirectory was set in the
  158. // outer config, use getUpgradeDownloadFilePath with its value instead.
  159. public static String getDefaultUpgradeDownloadFilePath(Context context) {
  160. return Psi.upgradeDownloadFilePath(defaultDataRootDirectory(context).getAbsolutePath());
  161. }
  162. // Returns the path where upgrade downloads will be paved relative to the configured
  163. // DataRootDirectory.
  164. public static String getUpgradeDownloadFilePath(String dataRootDirectoryPath) {
  165. return Psi.upgradeDownloadFilePath(dataRootDirectoryPath);
  166. }
  167. private static File defaultDataRootDirectory(Context context) {
  168. return context.getFileStreamPath("ca.psiphon.PsiphonTunnel.tunnel-core");
  169. }
  170. private PsiphonTunnel(HostService hostService, boolean shouldRouteThroughTunnelAutomatically) {
  171. mHostService = hostService;
  172. mVpnMode = new AtomicBoolean(false);
  173. mTunFd = new AtomicReference<ParcelFileDescriptor>();
  174. mLocalSocksProxyPort = new AtomicInteger(0);
  175. mRoutingThroughTunnel = new AtomicBoolean(false);
  176. mIsWaitingForNetworkConnectivity = new AtomicBoolean(false);
  177. mClientPlatformPrefix = new AtomicReference<String>("");
  178. mClientPlatformSuffix = new AtomicReference<String>("");
  179. mShouldRouteThroughTunnelAutomatically = shouldRouteThroughTunnelAutomatically;
  180. mActiveNetworkType = new AtomicReference<String>("");
  181. mActiveNetworkDNSServers = new AtomicReference<String>("");
  182. mNetworkMonitor = new NetworkMonitor(new NetworkMonitor.NetworkChangeListener() {
  183. @Override
  184. public void onChanged() {
  185. try {
  186. reconnectPsiphon();
  187. } catch (Exception e) {
  188. mHostService.onDiagnosticMessage("reconnect error: " + e);
  189. }
  190. }
  191. });
  192. }
  193. public Object clone() throws CloneNotSupportedException {
  194. throw new CloneNotSupportedException();
  195. }
  196. //----------------------------------------------------------------------------------------------
  197. // Public API
  198. //----------------------------------------------------------------------------------------------
  199. // To start, call in sequence: startRouting(), then startTunneling(). After startRouting()
  200. // succeeds, the caller must call stop() to clean up. These functions should not be called
  201. // concurrently. Do not call stop() while startRouting() or startTunneling() is in progress.
  202. // In case the host application requests manual control of routing through tunnel by calling
  203. // PsiphonTunnel.newPsiphonTunnel(HostService hostservice, shouldRouteThroughTunnelAutomatically = false)
  204. // it should also call routeThroughTunnel() at some point, usually after receiving onConnected() callback,
  205. // otherwise it will be called automatically.
  206. // Returns true when the VPN routing is established; returns false if the VPN could not
  207. // be started due to lack of prepare or revoked permissions (called should re-prepare and
  208. // try again); throws exception for other error conditions.
  209. public synchronized boolean startRouting() throws Exception {
  210. // Load tun2socks library embedded in the aar
  211. // If this method is called more than once with the same library name, the second and subsequent calls are ignored.
  212. // http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#loadLibrary%28java.lang.String%29
  213. mHostService.loadLibrary("tun2socks");
  214. return startVpn();
  215. }
  216. // Starts routing traffic via tunnel by starting tun2socks if it is not running already.
  217. // This will be called automatically right after tunnel gets connected in case the host application
  218. // did not request a manual control over this functionality, see PsiphonTunnel.newPsiphonTunnel
  219. public void routeThroughTunnel() {
  220. if (!mRoutingThroughTunnel.compareAndSet(false, true)) {
  221. return;
  222. }
  223. ParcelFileDescriptor tunFd = mTunFd.get();
  224. if (tunFd == null) {
  225. return;
  226. }
  227. String socksServerAddress = "127.0.0.1:" + Integer.toString(mLocalSocksProxyPort.get());
  228. String udpgwServerAddress = "127.0.0.1:" + Integer.toString(UDPGW_SERVER_PORT);
  229. // We may call routeThroughTunnel and stopRouteThroughTunnel more than once within the same
  230. // VPN session. Since stopTun2Socks() closes the FD passed to startTun2Socks() we will use a
  231. // dup of the original tun FD and close the original only when we call stopVpn().
  232. //
  233. // Note that ParcelFileDescriptor.dup() may throw an IOException.
  234. try {
  235. startTun2Socks(
  236. tunFd.dup(),
  237. VPN_INTERFACE_MTU,
  238. mPrivateAddress.mRouter,
  239. VPN_INTERFACE_NETMASK,
  240. socksServerAddress,
  241. udpgwServerAddress,
  242. true);
  243. mHostService.onDiagnosticMessage("routing through tunnel");
  244. // TODO: should double-check tunnel routing; see:
  245. // https://bitbucket.org/psiphon/psiphon-circumvention-system/src/1dc5e4257dca99790109f3bf374e8ab3a0ead4d7/Android/PsiphonAndroidLibrary/src/com/psiphon3/psiphonlibrary/TunnelCore.java?at=default#cl-779
  246. } catch (IOException e) {
  247. mHostService.onDiagnosticMessage("routing through tunnel error: " + e);
  248. }
  249. }
  250. public void stopRouteThroughTunnel() {
  251. if (mRoutingThroughTunnel.compareAndSet(true, false)) {
  252. stopTun2Socks();
  253. }
  254. }
  255. // Throws an exception in error conditions. In the case of an exception, the routing
  256. // started by startRouting() is not immediately torn down (this allows the caller to control
  257. // exactly when VPN routing is stopped); caller should call stop() to clean up.
  258. public synchronized void startTunneling(String embeddedServerEntries) throws Exception {
  259. startPsiphon(embeddedServerEntries);
  260. }
  261. // Note: to avoid deadlock, do not call directly from a HostService callback;
  262. // instead post to a Handler if necessary to trigger from a HostService callback.
  263. // For example, deadlock can occur when a Notice callback invokes stop() since stop() calls
  264. // Psi.stop() which will block waiting for tunnel-core Controller to shutdown which in turn
  265. // waits for Notice callback invoker to stop, meanwhile the callback thread has blocked waiting
  266. // for stop().
  267. public synchronized void stop() {
  268. stopVpn();
  269. stopPsiphon();
  270. mVpnMode.set(false);
  271. mLocalSocksProxyPort.set(0);
  272. }
  273. // Note: same deadlock note as stop().
  274. public synchronized void restartPsiphon() throws Exception {
  275. stopPsiphon();
  276. startPsiphon("");
  277. }
  278. public synchronized void reconnectPsiphon() throws Exception {
  279. Psi.reconnectTunnel();
  280. }
  281. public void setClientPlatformAffixes(String prefix, String suffix) {
  282. mClientPlatformPrefix.set(prefix);
  283. mClientPlatformSuffix.set(suffix);
  284. }
  285. public String exportExchangePayload() {
  286. return Psi.exportExchangePayload();
  287. }
  288. public boolean importExchangePayload(String payload) {
  289. return Psi.importExchangePayload(payload);
  290. }
  291. // Writes Go runtime profile information to a set of files in the specifiec output directory.
  292. // cpuSampleDurationSeconds and blockSampleDurationSeconds determines how to long to wait and
  293. // sample profiles that require active sampling. When set to 0, these profiles are skipped.
  294. public void writeRuntimeProfiles(String outputDirectory, int cpuSampleDurationSeconnds, int blockSampleDurationSeconds) {
  295. Psi.writeRuntimeProfiles(outputDirectory, cpuSampleDurationSeconnds, blockSampleDurationSeconds);
  296. }
  297. // The interface for managing the Psiphon feedback upload operations.
  298. // Warnings:
  299. // - Should not be used in the same process as PsiphonTunnel.
  300. // - Only a single instance of PsiphonTunnelFeedback should be used at a time. Using multiple
  301. // instances in parallel, or concurrently, will result in undefined behavior.
  302. public static class PsiphonTunnelFeedback {
  303. final private ExecutorService workQueue;
  304. final private ExecutorService callbackQueue;
  305. public PsiphonTunnelFeedback() {
  306. workQueue = Executors.newSingleThreadExecutor();
  307. callbackQueue = Executors.newSingleThreadExecutor();
  308. }
  309. @Override
  310. protected void finalize() throws Throwable {
  311. // Ensure the queues are cleaned up.
  312. shutdownAndAwaitTermination(callbackQueue);
  313. shutdownAndAwaitTermination(workQueue);
  314. super.finalize();
  315. }
  316. void shutdownAndAwaitTermination(ExecutorService pool) {
  317. try {
  318. // Wait a while for existing tasks to terminate
  319. if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
  320. pool.shutdownNow(); // Cancel currently executing tasks
  321. // Wait a while for tasks to respond to being cancelled
  322. if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
  323. System.err.println("PsiphonTunnelFeedback: pool did not terminate");
  324. return;
  325. }
  326. }
  327. } catch (InterruptedException ie) {
  328. // (Re-)Cancel if current thread also interrupted
  329. pool.shutdownNow();
  330. // Preserve interrupt status
  331. Thread.currentThread().interrupt();
  332. }
  333. }
  334. // Upload a feedback package to Psiphon Inc. The app collects feedback and diagnostics
  335. // information in a particular format, then calls this function to upload it for later
  336. // investigation. The feedback compatible config and upload path must be provided by
  337. // Psiphon Inc. This call is asynchronous and returns before the upload completes. The
  338. // operation has completed when sendFeedbackCompleted() is called on the provided
  339. // HostFeedbackHandler. The provided HostLogger will be called to log informational notices,
  340. // including warnings.
  341. //
  342. // Warnings:
  343. // - Only one active upload is supported at a time. An ongoing upload will be cancelled if
  344. // this function is called again before it completes.
  345. // - An ongoing feedback upload started with startSendFeedback() should be stopped with
  346. // stopSendFeedback() before the process exits. This ensures that any underlying resources
  347. // are cleaned up; failing to do so may result in data store corruption or other undefined
  348. // behavior.
  349. // - PsiphonTunnel.startTunneling and startSendFeedback both make an attempt to migrate
  350. // persistent files from legacy locations in a one-time operation. If these functions are
  351. // called in parallel, then there is a chance that the migration attempts could execute at
  352. // the same time and result in non-fatal errors in one, or both, of the migration
  353. // operations.
  354. public void startSendFeedback(Context context, HostFeedbackHandler feedbackHandler, HostLogger logger,
  355. String feedbackConfigJson, String diagnosticsJson, String uploadPath,
  356. String clientPlatformPrefix, String clientPlatformSuffix) {
  357. workQueue.submit(new Runnable() {
  358. @Override
  359. public void run() {
  360. try {
  361. // Adds fields used in feedback upload, e.g. client platform.
  362. String psiphonConfig = buildPsiphonConfig(context, logger, feedbackConfigJson,
  363. clientPlatformPrefix, clientPlatformSuffix, false, 0);
  364. Psi.startSendFeedback(psiphonConfig, diagnosticsJson, uploadPath,
  365. new PsiphonProviderFeedbackHandler() {
  366. @Override
  367. public void sendFeedbackCompleted(java.lang.Exception e) {
  368. callbackQueue.submit(new Runnable() {
  369. @Override
  370. public void run() {
  371. feedbackHandler.sendFeedbackCompleted(e);
  372. }
  373. });
  374. }
  375. },
  376. new PsiphonProviderNetwork() {
  377. @Override
  378. public long hasNetworkConnectivity() {
  379. boolean hasConnectivity = PsiphonTunnel.hasNetworkConnectivity(context);
  380. // TODO: change to bool return value once gobind supports that type
  381. return hasConnectivity ? 1 : 0;
  382. }
  383. @Override
  384. public String getNetworkID() {
  385. return PsiphonTunnel.getNetworkID(context);
  386. }
  387. @Override
  388. public String iPv6Synthesize(String IPv4Addr) {
  389. // Unused on Android.
  390. return PsiphonTunnel.iPv6Synthesize(IPv4Addr);
  391. }
  392. @Override
  393. public long hasIPv6Route() {
  394. return PsiphonTunnel.hasIPv6Route(context, logger);
  395. }
  396. },
  397. new PsiphonProviderNoticeHandler() {
  398. @Override
  399. public void notice(String noticeJSON) {
  400. try {
  401. JSONObject notice = new JSONObject(noticeJSON);
  402. String noticeType = notice.getString("noticeType");
  403. if (noticeType == null) {
  404. return;
  405. }
  406. JSONObject data = notice.getJSONObject("data");
  407. if (data == null) {
  408. return;
  409. }
  410. String diagnosticMessage = noticeType + ": " + data.toString();
  411. callbackQueue.submit(new Runnable() {
  412. @Override
  413. public void run() {
  414. logger.onDiagnosticMessage(diagnosticMessage);
  415. }
  416. });
  417. } catch (java.lang.Exception e) {
  418. callbackQueue.submit(new Runnable() {
  419. @Override
  420. public void run() {
  421. logger.onDiagnosticMessage("Error handling notice " + e.toString());
  422. }
  423. });
  424. }
  425. }
  426. },
  427. false, // Do not use IPv6 synthesizer for Android
  428. true // Use hasIPv6Route on Android
  429. );
  430. } catch (java.lang.Exception e) {
  431. callbackQueue.submit(new Runnable() {
  432. @Override
  433. public void run() {
  434. feedbackHandler.sendFeedbackCompleted(new Exception("Error sending feedback", e));
  435. }
  436. });
  437. }
  438. }
  439. });
  440. }
  441. // Interrupt an in-progress feedback upload operation started with startSendFeedback(). This
  442. // call is asynchronous and returns a future which is fulfilled when the underlying stop
  443. // operation completes.
  444. public Future<Void> stopSendFeedback() {
  445. return workQueue.submit(new Runnable() {
  446. @Override
  447. public void run() {
  448. Psi.stopSendFeedback();
  449. }
  450. }, null);
  451. }
  452. }
  453. //----------------------------------------------------------------------------------------------
  454. // VPN Routing
  455. //----------------------------------------------------------------------------------------------
  456. private final static String VPN_INTERFACE_NETMASK = "255.255.255.0";
  457. private final static int VPN_INTERFACE_MTU = 1500;
  458. private final static int UDPGW_SERVER_PORT = 7300;
  459. // Note: Atomic variables used for getting/setting local proxy port, routing flag, and
  460. // tun fd, as these functions may be called via PsiphonProvider callbacks. Do not use
  461. // synchronized functions as stop() is synchronized and a deadlock is possible as callbacks
  462. // can be called while stop holds the lock.
  463. @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
  464. private boolean startVpn() throws Exception {
  465. mVpnMode.set(true);
  466. mPrivateAddress = selectPrivateAddress();
  467. Locale previousLocale = Locale.getDefault();
  468. final String errorMessage = "startVpn failed";
  469. try {
  470. // Workaround for https://code.google.com/p/android/issues/detail?id=61096
  471. Locale.setDefault(new Locale("en"));
  472. int mtu = VPN_INTERFACE_MTU;
  473. String dnsResolver = mPrivateAddress.mRouter;
  474. ParcelFileDescriptor tunFd =
  475. ((VpnService.Builder) mHostService.newVpnServiceBuilder())
  476. .setSession(mHostService.getAppName())
  477. .setMtu(mtu)
  478. .addAddress(mPrivateAddress.mIpAddress, mPrivateAddress.mPrefixLength)
  479. .addRoute("0.0.0.0", 0)
  480. .addRoute(mPrivateAddress.mSubnet, mPrivateAddress.mPrefixLength)
  481. .addDnsServer(dnsResolver)
  482. .establish();
  483. if (tunFd == null) {
  484. // As per http://developer.android.com/reference/android/net/VpnService.Builder.html#establish%28%29,
  485. // this application is no longer prepared or was revoked.
  486. return false;
  487. }
  488. mTunFd.set(tunFd);
  489. mRoutingThroughTunnel.set(false);
  490. mHostService.onDiagnosticMessage("VPN established");
  491. } catch(IllegalArgumentException e) {
  492. throw new Exception(errorMessage, e);
  493. } catch(IllegalStateException e) {
  494. throw new Exception(errorMessage, e);
  495. } catch(SecurityException e) {
  496. throw new Exception(errorMessage, e);
  497. } finally {
  498. // Restore the original locale.
  499. Locale.setDefault(previousLocale);
  500. }
  501. return true;
  502. }
  503. @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
  504. private ParcelFileDescriptor startDummyVpn(VpnService.Builder vpnServiceBuilder) throws Exception {
  505. PrivateAddress privateAddress = selectPrivateAddress();
  506. Locale previousLocale = Locale.getDefault();
  507. final String errorMessage = "startDummyVpn failed";
  508. final ParcelFileDescriptor tunFd;
  509. try {
  510. // Workaround for https://code.google.com/p/android/issues/detail?id=61096
  511. Locale.setDefault(new Locale("en"));
  512. int mtu = VPN_INTERFACE_MTU;
  513. String dnsResolver = privateAddress.mRouter;
  514. tunFd = vpnServiceBuilder
  515. .setSession(mHostService.getAppName())
  516. .setMtu(mtu)
  517. .addAddress(privateAddress.mIpAddress, privateAddress.mPrefixLength)
  518. .addRoute("0.0.0.0", 0)
  519. .addRoute(privateAddress.mSubnet, privateAddress.mPrefixLength)
  520. .addDnsServer(dnsResolver)
  521. .establish();
  522. } catch(IllegalArgumentException e) {
  523. throw new Exception(errorMessage, e);
  524. } catch(IllegalStateException e) {
  525. throw new Exception(errorMessage, e);
  526. } catch(SecurityException e) {
  527. throw new Exception(errorMessage, e);
  528. } finally {
  529. // Restore the original locale.
  530. Locale.setDefault(previousLocale);
  531. }
  532. return tunFd;
  533. }
  534. private boolean isVpnMode() {
  535. return mVpnMode.get();
  536. }
  537. private void setLocalSocksProxyPort(int port) {
  538. mLocalSocksProxyPort.set(port);
  539. }
  540. private void stopVpn() {
  541. stopTun2Socks();
  542. ParcelFileDescriptor tunFd = mTunFd.getAndSet(null);
  543. if (tunFd != null) {
  544. try {
  545. tunFd.close();
  546. } catch (IOException e) {
  547. }
  548. }
  549. mRoutingThroughTunnel.set(false);
  550. }
  551. //----------------------------------------------------------------------------------------------
  552. // PsiphonProvider (Core support) interface implementation
  553. //----------------------------------------------------------------------------------------------
  554. // The PsiphonProvider functions are called from Go, and must be public to be accessible
  555. // via the gobind mechanim. To avoid making internal implementation functions public,
  556. // PsiphonProviderShim is used as a wrapper.
  557. private class PsiphonProviderShim implements PsiphonProvider {
  558. private PsiphonTunnel mPsiphonTunnel;
  559. public PsiphonProviderShim(PsiphonTunnel psiphonTunnel) {
  560. mPsiphonTunnel = psiphonTunnel;
  561. }
  562. @Override
  563. public void notice(String noticeJSON) {
  564. mPsiphonTunnel.notice(noticeJSON);
  565. }
  566. @Override
  567. public String bindToDevice(long fileDescriptor) throws Exception {
  568. return mPsiphonTunnel.bindToDevice(fileDescriptor);
  569. }
  570. @Override
  571. public long hasNetworkConnectivity() {
  572. return mPsiphonTunnel.hasNetworkConnectivity();
  573. }
  574. @Override
  575. public String getDNSServersAsString() {
  576. return mPsiphonTunnel.getDNSServers(mHostService.getContext(), mHostService);
  577. }
  578. @Override
  579. public String iPv6Synthesize(String IPv4Addr) {
  580. return PsiphonTunnel.iPv6Synthesize(IPv4Addr);
  581. }
  582. @Override
  583. public long hasIPv6Route() {
  584. return PsiphonTunnel.hasIPv6Route(mHostService.getContext(), mHostService);
  585. }
  586. @Override
  587. public String getNetworkID() {
  588. return PsiphonTunnel.getNetworkID(mHostService.getContext());
  589. }
  590. }
  591. private void notice(String noticeJSON) {
  592. handlePsiphonNotice(noticeJSON);
  593. }
  594. @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
  595. private String bindToDevice(long fileDescriptor) throws Exception {
  596. if (!((VpnService)mHostService.getVpnService()).protect((int)fileDescriptor)) {
  597. throw new Exception("protect socket failed");
  598. }
  599. return "";
  600. }
  601. private long hasNetworkConnectivity() {
  602. boolean hasConnectivity = hasNetworkConnectivity(mHostService.getContext());
  603. boolean wasWaitingForNetworkConnectivity = mIsWaitingForNetworkConnectivity.getAndSet(!hasConnectivity);
  604. // HasNetworkConnectivity may be called many times, but only invoke
  605. // callbacks once per loss or resumption of connectivity, so, e.g.,
  606. // the HostService may log a single message.
  607. if (!hasConnectivity && !wasWaitingForNetworkConnectivity) {
  608. mHostService.onStartedWaitingForNetworkConnectivity();
  609. } else if (hasConnectivity && wasWaitingForNetworkConnectivity) {
  610. mHostService.onStoppedWaitingForNetworkConnectivity();
  611. }
  612. // TODO: change to bool return value once gobind supports that type
  613. return hasConnectivity ? 1 : 0;
  614. }
  615. private String getDNSServers(Context context, HostLogger logger) {
  616. // Use the DNS servers set by mNetworkMonitor,
  617. // mActiveNetworkDNSServers, when available. It's the most reliable
  618. // mechanism. Otherwise fallback to getActiveNetworkDNSServers.
  619. //
  620. // mActiveNetworkDNSServers is not available on API < 21
  621. // (LOLLIPOP). mActiveNetworkDNSServers may also be temporarily
  622. // unavailable if the last active network has been lost and no new
  623. // one has yet replaced it.
  624. String servers = mActiveNetworkDNSServers.get();
  625. if (servers != "") {
  626. return servers;
  627. }
  628. try {
  629. // Use the workaround, comma-delimited format required for gobind.
  630. servers = TextUtils.join(",", getActiveNetworkDNSServers(context, mVpnMode.get()));
  631. } catch (Exception e) {
  632. logger.onDiagnosticMessage("failed to get active network DNS resolver: " + e.getMessage());
  633. // Alternate DNS servers will be provided by psiphon-tunnel-core
  634. // config or tactics.
  635. }
  636. return servers;
  637. }
  638. private static String iPv6Synthesize(String IPv4Addr) {
  639. // Unused on Android.
  640. return IPv4Addr;
  641. }
  642. private static long hasIPv6Route(Context context, HostLogger logger) {
  643. boolean hasRoute = false;
  644. try {
  645. hasRoute = hasIPv6Route(context);
  646. } catch (Exception e) {
  647. logger.onDiagnosticMessage("failed to check IPv6 route: " + e.getMessage());
  648. }
  649. // TODO: change to bool return value once gobind supports that type
  650. return hasRoute ? 1 : 0;
  651. }
  652. private static String getNetworkID(Context context) {
  653. // TODO: getActiveNetworkInfo is deprecated in API 29; once
  654. // getActiveNetworkInfo is no longer available, use
  655. // mActiveNetworkType which is updated by mNetworkMonitor.
  656. // The network ID contains potential PII. In tunnel-core, the network ID
  657. // is used only locally in the client and not sent to the server.
  658. //
  659. // See network ID requirements here:
  660. // https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter
  661. String networkID = "UNKNOWN";
  662. ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  663. NetworkInfo activeNetworkInfo = null;
  664. try {
  665. activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
  666. } catch (java.lang.Exception e) {
  667. // May get exceptions due to missing permissions like android.permission.ACCESS_NETWORK_STATE.
  668. // Apps using the Psiphon Library and lacking android.permission.ACCESS_NETWORK_STATE will
  669. // proceed and use tactics, but with "UNKNOWN" as the sole network ID.
  670. }
  671. if (activeNetworkInfo != null && activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
  672. networkID = "WIFI";
  673. try {
  674. WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
  675. WifiInfo wifiInfo = wifiManager.getConnectionInfo();
  676. if (wifiInfo != null) {
  677. String wifiNetworkID = wifiInfo.getBSSID();
  678. if (wifiNetworkID.equals("02:00:00:00:00:00")) {
  679. // "02:00:00:00:00:00" is reported when the app does not have the ACCESS_COARSE_LOCATION permission:
  680. // https://developer.android.com/about/versions/marshmallow/android-6.0-changes#behavior-hardware-id
  681. // The Psiphon client should allow the user to opt-in to this permission. If they decline, fail over
  682. // to using the WiFi IP address.
  683. wifiNetworkID = String.valueOf(wifiInfo.getIpAddress());
  684. }
  685. networkID += "-" + wifiNetworkID;
  686. }
  687. } catch (java.lang.Exception e) {
  688. // May get exceptions due to missing permissions like android.permission.ACCESS_WIFI_STATE.
  689. // Fall through and use just "WIFI"
  690. }
  691. } else if (activeNetworkInfo != null && activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
  692. networkID = "MOBILE";
  693. try {
  694. TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
  695. if (telephonyManager != null) {
  696. networkID += "-" + telephonyManager.getNetworkOperator();
  697. }
  698. } catch (java.lang.Exception e) {
  699. // May get exceptions due to missing permissions.
  700. // Fall through and use just "MOBILE"
  701. }
  702. }
  703. return networkID;
  704. }
  705. //----------------------------------------------------------------------------------------------
  706. // Psiphon Tunnel Core
  707. //----------------------------------------------------------------------------------------------
  708. private void startPsiphon(String embeddedServerEntries) throws Exception {
  709. stopPsiphon();
  710. mIsWaitingForNetworkConnectivity.set(false);
  711. mHostService.onDiagnosticMessage("starting Psiphon library");
  712. try {
  713. // mNetworkMonitor.start() will wait up to 1 second before returning to give the network
  714. // callback a chance to populate active network properties before we start the tunnel.
  715. mNetworkMonitor.start(mHostService.getContext());
  716. Psi.start(
  717. loadPsiphonConfig(mHostService.getContext()),
  718. embeddedServerEntries,
  719. "",
  720. new PsiphonProviderShim(this),
  721. isVpnMode(),
  722. false, // Do not use IPv6 synthesizer for Android
  723. true // Use hasIPv6Route on Android
  724. );
  725. } catch (java.lang.Exception e) {
  726. throw new Exception("failed to start Psiphon library", e);
  727. }
  728. mHostService.onDiagnosticMessage("Psiphon library started");
  729. }
  730. private void stopPsiphon() {
  731. mHostService.onDiagnosticMessage("stopping Psiphon library");
  732. mNetworkMonitor.stop(mHostService.getContext());
  733. Psi.stop();
  734. mHostService.onDiagnosticMessage("Psiphon library stopped");
  735. }
  736. private String loadPsiphonConfig(Context context)
  737. throws IOException, JSONException, Exception {
  738. return buildPsiphonConfig(context, mHostService, mHostService.getPsiphonConfig(),
  739. mClientPlatformPrefix.get(), mClientPlatformSuffix.get(), isVpnMode(),
  740. mLocalSocksProxyPort.get());
  741. }
  742. private static String buildPsiphonConfig(Context context, HostLogger logger, String psiphonConfig,
  743. String clientPlatformPrefix, String clientPlatformSuffix,
  744. boolean isVpnMode, Integer localSocksProxyPort)
  745. throws IOException, JSONException, Exception {
  746. // Load settings from the raw resource JSON config file and
  747. // update as necessary. Then write JSON to disk for the Go client.
  748. JSONObject json = new JSONObject(psiphonConfig);
  749. // On Android, this directory must be set to the app private storage area.
  750. // The Psiphon library won't be able to use its current working directory
  751. // and the standard temporary directories do not exist.
  752. if (!json.has("DataRootDirectory")) {
  753. File dataRootDirectory = defaultDataRootDirectory(context);
  754. if (!dataRootDirectory.exists()) {
  755. boolean created = dataRootDirectory.mkdir();
  756. if (!created) {
  757. throw new Exception("failed to create data root directory: " + dataRootDirectory.getPath());
  758. }
  759. }
  760. json.put("DataRootDirectory", defaultDataRootDirectory(context));
  761. }
  762. // Migrate datastore files from legacy directory.
  763. if (!json.has("DataStoreDirectory")) {
  764. json.put("MigrateDataStoreDirectory", context.getFilesDir());
  765. }
  766. // Migrate remote server list downloads from legacy location.
  767. if (!json.has("RemoteServerListDownloadFilename")) {
  768. File remoteServerListDownload = new File(context.getFilesDir(), "remote_server_list");
  769. json.put("MigrateRemoteServerListDownloadFilename", remoteServerListDownload.getAbsolutePath());
  770. }
  771. // Migrate obfuscated server list download files from legacy directory.
  772. File oslDownloadDir = new File(context.getFilesDir(), "osl");
  773. json.put("MigrateObfuscatedServerListDownloadDirectory", oslDownloadDir.getAbsolutePath());
  774. // Continue to run indefinitely until connected
  775. if (!json.has("EstablishTunnelTimeoutSeconds")) {
  776. json.put("EstablishTunnelTimeoutSeconds", 0);
  777. }
  778. json.put("EmitBytesTransferred", true);
  779. if (localSocksProxyPort != 0 && (!json.has("LocalSocksProxyPort") || json.getInt("LocalSocksProxyPort") == 0)) {
  780. // When mLocalSocksProxyPort is set, tun2socks is already configured
  781. // to use that port value. So we force use of the same port.
  782. // A side-effect of this is that changing the SOCKS port preference
  783. // has no effect with restartPsiphon(), a full stop() is necessary.
  784. json.put("LocalSocksProxyPort", localSocksProxyPort);
  785. }
  786. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
  787. try {
  788. json.put(
  789. "TrustedCACertificatesFilename",
  790. setupTrustedCertificates(context, logger));
  791. } catch (Exception e) {
  792. logger.onDiagnosticMessage(e.getMessage());
  793. }
  794. }
  795. json.put("DeviceRegion", getDeviceRegion(context));
  796. StringBuilder clientPlatform = new StringBuilder();
  797. if (clientPlatformPrefix.length() > 0) {
  798. clientPlatform.append(clientPlatformPrefix);
  799. }
  800. clientPlatform.append("Android_");
  801. clientPlatform.append(Build.VERSION.RELEASE);
  802. clientPlatform.append("_");
  803. clientPlatform.append(context.getPackageName());
  804. if (clientPlatformSuffix.length() > 0) {
  805. clientPlatform.append(clientPlatformSuffix);
  806. }
  807. json.put("ClientPlatform", clientPlatform.toString().replaceAll("[^\\w\\-\\.]", "_"));
  808. return json.toString();
  809. }
  810. private void handlePsiphonNotice(String noticeJSON) {
  811. try {
  812. // All notices are sent on as diagnostic messages
  813. // except those that may contain private user data.
  814. boolean diagnostic = true;
  815. JSONObject notice = new JSONObject(noticeJSON);
  816. String noticeType = notice.getString("noticeType");
  817. if (noticeType.equals("Tunnels")) {
  818. int count = notice.getJSONObject("data").getInt("count");
  819. if (count == 0) {
  820. mHostService.onConnecting();
  821. } else if (count == 1) {
  822. if (isVpnMode() && mShouldRouteThroughTunnelAutomatically) {
  823. routeThroughTunnel();
  824. }
  825. mHostService.onConnected();
  826. }
  827. // count > 1 is an additional multi-tunnel establishment, and not reported.
  828. } else if (noticeType.equals("AvailableEgressRegions")) {
  829. JSONArray egressRegions = notice.getJSONObject("data").getJSONArray("regions");
  830. ArrayList<String> regions = new ArrayList<String>();
  831. for (int i=0; i<egressRegions.length(); i++) {
  832. regions.add(egressRegions.getString(i));
  833. }
  834. mHostService.onAvailableEgressRegions(regions);
  835. } else if (noticeType.equals("SocksProxyPortInUse")) {
  836. mHostService.onSocksProxyPortInUse(notice.getJSONObject("data").getInt("port"));
  837. } else if (noticeType.equals("HttpProxyPortInUse")) {
  838. mHostService.onHttpProxyPortInUse(notice.getJSONObject("data").getInt("port"));
  839. } else if (noticeType.equals("ListeningSocksProxyPort")) {
  840. int port = notice.getJSONObject("data").getInt("port");
  841. setLocalSocksProxyPort(port);
  842. mHostService.onListeningSocksProxyPort(port);
  843. } else if (noticeType.equals("ListeningHttpProxyPort")) {
  844. int port = notice.getJSONObject("data").getInt("port");
  845. mHostService.onListeningHttpProxyPort(port);
  846. } else if (noticeType.equals("UpstreamProxyError")) {
  847. diagnostic = false;
  848. mHostService.onUpstreamProxyError(notice.getJSONObject("data").getString("message"));
  849. } else if (noticeType.equals("ClientUpgradeDownloaded")) {
  850. mHostService.onClientUpgradeDownloaded(notice.getJSONObject("data").getString("filename"));
  851. } else if (noticeType.equals("ClientIsLatestVersion")) {
  852. mHostService.onClientIsLatestVersion();
  853. } else if (noticeType.equals("Homepage")) {
  854. mHostService.onHomepage(notice.getJSONObject("data").getString("url"));
  855. } else if (noticeType.equals("ClientRegion")) {
  856. mHostService.onClientRegion(notice.getJSONObject("data").getString("region"));
  857. } else if (noticeType.equals("ClientAddress")) {
  858. diagnostic = false;
  859. mHostService.onClientAddress(notice.getJSONObject("data").getString("address"));
  860. } else if (noticeType.equals("SplitTunnelRegions")) {
  861. JSONArray splitTunnelRegions = notice.getJSONObject("data").getJSONArray("regions");
  862. ArrayList<String> regions = new ArrayList<String>();
  863. for (int i=0; i<splitTunnelRegions.length(); i++) {
  864. regions.add(splitTunnelRegions.getString(i));
  865. }
  866. mHostService.onSplitTunnelRegions(regions);
  867. } else if (noticeType.equals("Untunneled")) {
  868. diagnostic = false;
  869. mHostService.onUntunneledAddress(notice.getJSONObject("data").getString("address"));
  870. } else if (noticeType.equals("BytesTransferred")) {
  871. diagnostic = false;
  872. JSONObject data = notice.getJSONObject("data");
  873. mHostService.onBytesTransferred(data.getLong("sent"), data.getLong("received"));
  874. } else if (noticeType.equals("ActiveAuthorizationIDs")) {
  875. JSONArray activeAuthorizationIDs = notice.getJSONObject("data").getJSONArray("IDs");
  876. ArrayList<String> authorizations = new ArrayList<String>();
  877. for (int i=0; i<activeAuthorizationIDs.length(); i++) {
  878. authorizations.add(activeAuthorizationIDs.getString(i));
  879. }
  880. mHostService.onActiveAuthorizationIDs(authorizations);
  881. } else if (noticeType.equals("TrafficRateLimits")) {
  882. JSONObject data = notice.getJSONObject("data");
  883. mHostService.onTrafficRateLimits(
  884. data.getLong("upstreamBytesPerSecond"), data.getLong("downstreamBytesPerSecond"));
  885. } else if (noticeType.equals("Exiting")) {
  886. mHostService.onExiting();
  887. } else if (noticeType.equals("ActiveTunnel")) {
  888. if (isVpnMode()) {
  889. if (notice.getJSONObject("data").getBoolean("isTCS")) {
  890. disableUdpGwKeepalive();
  891. } else {
  892. enableUdpGwKeepalive();
  893. }
  894. }
  895. } else if (noticeType.equals("ApplicationParameters")) {
  896. mHostService.onApplicationParameters(
  897. notice.getJSONObject("data").get("parameters"));
  898. } else if (noticeType.equals("ServerAlert")) {
  899. JSONArray actionURLs = notice.getJSONObject("data").getJSONArray("actionURLs");
  900. ArrayList<String> actionURLsList = new ArrayList<String>();
  901. for (int i=0; i<actionURLs.length(); i++) {
  902. actionURLsList.add(actionURLs.getString(i));
  903. }
  904. mHostService.onServerAlert(
  905. notice.getJSONObject("data").getString("reason"),
  906. notice.getJSONObject("data").getString("subject"),
  907. actionURLsList);
  908. }
  909. if (diagnostic) {
  910. String diagnosticMessage = noticeType + ": " + notice.getJSONObject("data").toString();
  911. mHostService.onDiagnosticMessage(diagnosticMessage);
  912. }
  913. } catch (JSONException e) {
  914. // Ignore notice
  915. }
  916. }
  917. private static String setupTrustedCertificates(Context context, HostLogger logger) throws Exception {
  918. // Copy the Android system CA store to a local, private cert bundle file.
  919. //
  920. // This results in a file that can be passed to SSL_CTX_load_verify_locations
  921. // for use with OpenSSL modes in tunnel-core.
  922. // https://www.openssl.org/docs/manmaster/ssl/SSL_CTX_load_verify_locations.html
  923. //
  924. // TODO: to use the path mode of load_verify_locations would require emulating
  925. // the filename scheme used by c_rehash:
  926. // https://www.openssl.org/docs/manmaster/apps/c_rehash.html
  927. // http://stackoverflow.com/questions/19237167/the-new-subject-hash-openssl-algorithm-differs
  928. File directory = context.getDir("PsiphonCAStore", Context.MODE_PRIVATE);
  929. final String errorMessage = "copy AndroidCAStore failed";
  930. try {
  931. File file = new File(directory, "certs.dat");
  932. // Pave a fresh copy on every run, which ensures we're not using old certs.
  933. // Note: assumes KeyStore doesn't return revoked certs.
  934. //
  935. // TODO: this takes under 1 second, but should we avoid repaving every time?
  936. file.delete();
  937. PrintStream output = null;
  938. try {
  939. output = new PrintStream(new FileOutputStream(file));
  940. KeyStore keyStore;
  941. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
  942. keyStore = KeyStore.getInstance("AndroidCAStore");
  943. keyStore.load(null, null);
  944. } else {
  945. keyStore = KeyStore.getInstance("BKS");
  946. FileInputStream inputStream = new FileInputStream("/etc/security/cacerts.bks");
  947. try {
  948. keyStore.load(inputStream, "changeit".toCharArray());
  949. } finally {
  950. if (inputStream != null) {
  951. inputStream.close();
  952. }
  953. }
  954. }
  955. Enumeration<String> aliases = keyStore.aliases();
  956. while (aliases.hasMoreElements()) {
  957. String alias = aliases.nextElement();
  958. X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
  959. output.println("-----BEGIN CERTIFICATE-----");
  960. String pemCert = new String(Base64.encode(cert.getEncoded(), Base64.NO_WRAP), "UTF-8");
  961. // OpenSSL appears to reject the default linebreaking done by Base64.encode,
  962. // so we manually linebreak every 64 characters
  963. for (int i = 0; i < pemCert.length() ; i+= 64) {
  964. output.println(pemCert.substring(i, Math.min(i + 64, pemCert.length())));
  965. }
  966. output.println("-----END CERTIFICATE-----");
  967. }
  968. logger.onDiagnosticMessage("prepared PsiphonCAStore");
  969. return file.getAbsolutePath();
  970. } finally {
  971. if (output != null) {
  972. output.close();
  973. }
  974. }
  975. } catch (KeyStoreException e) {
  976. throw new Exception(errorMessage, e);
  977. } catch (NoSuchAlgorithmException e) {
  978. throw new Exception(errorMessage, e);
  979. } catch (CertificateException e) {
  980. throw new Exception(errorMessage, e);
  981. } catch (IOException e) {
  982. throw new Exception(errorMessage, e);
  983. }
  984. }
  985. private static String getDeviceRegion(Context context) {
  986. String region = "";
  987. TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
  988. if (telephonyManager != null) {
  989. region = telephonyManager.getSimCountryIso();
  990. if (region == null) {
  991. region = "";
  992. }
  993. if (region.length() == 0 && telephonyManager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
  994. region = telephonyManager.getNetworkCountryIso();
  995. if (region == null) {
  996. region = "";
  997. }
  998. }
  999. }
  1000. if (region.length() == 0) {
  1001. Locale defaultLocale = Locale.getDefault();
  1002. if (defaultLocale != null) {
  1003. region = defaultLocale.getCountry();
  1004. }
  1005. }
  1006. return region.toUpperCase(Locale.US);
  1007. }
  1008. //----------------------------------------------------------------------------------------------
  1009. // Tun2Socks
  1010. //----------------------------------------------------------------------------------------------
  1011. @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
  1012. private void startTun2Socks(
  1013. final ParcelFileDescriptor vpnInterfaceFileDescriptor,
  1014. final int vpnInterfaceMTU,
  1015. final String vpnIpAddress,
  1016. final String vpnNetMask,
  1017. final String socksServerAddress,
  1018. final String udpgwServerAddress,
  1019. final boolean udpgwTransparentDNS) {
  1020. if (mTun2SocksThread != null) {
  1021. return;
  1022. }
  1023. mTun2SocksThread = new Thread(new Runnable() {
  1024. @Override
  1025. public void run() {
  1026. runTun2Socks(
  1027. vpnInterfaceFileDescriptor.detachFd(),
  1028. vpnInterfaceMTU,
  1029. vpnIpAddress,
  1030. vpnNetMask,
  1031. socksServerAddress,
  1032. udpgwServerAddress,
  1033. udpgwTransparentDNS ? 1 : 0);
  1034. }
  1035. });
  1036. mTun2SocksThread.start();
  1037. mHostService.onDiagnosticMessage("tun2socks started");
  1038. }
  1039. private void stopTun2Socks() {
  1040. if (mTun2SocksThread != null) {
  1041. try {
  1042. terminateTun2Socks();
  1043. mTun2SocksThread.join();
  1044. } catch (InterruptedException e) {
  1045. Thread.currentThread().interrupt();
  1046. }
  1047. mTun2SocksThread = null;
  1048. mHostService.onDiagnosticMessage("tun2socks stopped");
  1049. }
  1050. }
  1051. public static void logTun2Socks(String level, String channel, String msg) {
  1052. String logMsg = "tun2socks: " + level + "(" + channel + "): " + msg;
  1053. mPsiphonTunnel.mHostService.onDiagnosticMessage(logMsg);
  1054. }
  1055. private native static int runTun2Socks(
  1056. int vpnInterfaceFileDescriptor,
  1057. int vpnInterfaceMTU,
  1058. String vpnIpAddress,
  1059. String vpnNetMask,
  1060. String socksServerAddress,
  1061. String udpgwServerAddress,
  1062. int udpgwTransparentDNS);
  1063. private native static int terminateTun2Socks();
  1064. private native static int enableUdpGwKeepalive();
  1065. private native static int disableUdpGwKeepalive();
  1066. //----------------------------------------------------------------------------------------------
  1067. // Implementation: Network Utils
  1068. //----------------------------------------------------------------------------------------------
  1069. private static boolean hasNetworkConnectivity(Context context) {
  1070. ConnectivityManager connectivityManager =
  1071. (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  1072. if (connectivityManager == null) {
  1073. return false;
  1074. }
  1075. NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
  1076. return networkInfo != null && networkInfo.isConnected();
  1077. }
  1078. private static class PrivateAddress {
  1079. final public String mIpAddress;
  1080. final public String mSubnet;
  1081. final public int mPrefixLength;
  1082. final public String mRouter;
  1083. public PrivateAddress(String ipAddress, String subnet, int prefixLength, String router) {
  1084. mIpAddress = ipAddress;
  1085. mSubnet = subnet;
  1086. mPrefixLength = prefixLength;
  1087. mRouter = router;
  1088. }
  1089. }
  1090. private static PrivateAddress selectPrivateAddress() throws Exception {
  1091. // Select one of 10.0.0.1, 172.16.0.1, or 192.168.0.1 depending on
  1092. // which private address range isn't in use.
  1093. Map<String, PrivateAddress> candidates = new HashMap<String, PrivateAddress>();
  1094. candidates.put( "10", new PrivateAddress("10.0.0.1", "10.0.0.0", 8, "10.0.0.2"));
  1095. candidates.put("172", new PrivateAddress("172.16.0.1", "172.16.0.0", 12, "172.16.0.2"));
  1096. candidates.put("192", new PrivateAddress("192.168.0.1", "192.168.0.0", 16, "192.168.0.2"));
  1097. candidates.put("169", new PrivateAddress("169.254.1.1", "169.254.1.0", 24, "169.254.1.2"));
  1098. Enumeration<NetworkInterface> netInterfaces;
  1099. try {
  1100. netInterfaces = NetworkInterface.getNetworkInterfaces();
  1101. } catch (SocketException e) {
  1102. throw new Exception("selectPrivateAddress failed", e);
  1103. }
  1104. if (netInterfaces == null) {
  1105. throw new Exception("no network interfaces found");
  1106. }
  1107. for (NetworkInterface netInterface : Collections.list(netInterfaces)) {
  1108. for (InetAddress inetAddress : Collections.list(netInterface.getInetAddresses())) {
  1109. if (inetAddress instanceof Inet4Address) {
  1110. String ipAddress = inetAddress.getHostAddress();
  1111. if (ipAddress.startsWith("10.")) {
  1112. candidates.remove("10");
  1113. }
  1114. else if (
  1115. ipAddress.length() >= 6 &&
  1116. ipAddress.substring(0, 6).compareTo("172.16") >= 0 &&
  1117. ipAddress.substring(0, 6).compareTo("172.31") <= 0) {
  1118. candidates.remove("172");
  1119. }
  1120. else if (ipAddress.startsWith("192.168")) {
  1121. candidates.remove("192");
  1122. }
  1123. }
  1124. }
  1125. }
  1126. if (candidates.size() > 0) {
  1127. return candidates.values().iterator().next();
  1128. }
  1129. throw new Exception("no private address available");
  1130. }
  1131. private static Collection<String> getActiveNetworkDNSServers(Context context, boolean isVpnMode)
  1132. throws Exception {
  1133. ArrayList<String> servers = new ArrayList<String>();
  1134. for (InetAddress serverAddress : getActiveNetworkDNSServerAddresses(context, isVpnMode)) {
  1135. String server = serverAddress.toString();
  1136. // strip the leading slash e.g., "/192.168.1.1"
  1137. if (server.startsWith("/")) {
  1138. server = server.substring(1);
  1139. }
  1140. servers.add(server);
  1141. }
  1142. if (servers.isEmpty()) {
  1143. throw new Exception("no active network DNS resolver");
  1144. }
  1145. return servers;
  1146. }
  1147. private static Collection<InetAddress> getActiveNetworkDNSServerAddresses(Context context, boolean isVpnMode)
  1148. throws Exception {
  1149. final String errorMessage = "getActiveNetworkDNSServerAddresses failed";
  1150. ArrayList<InetAddress> dnsAddresses = new ArrayList<InetAddress>();
  1151. ConnectivityManager connectivityManager =
  1152. (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  1153. if (connectivityManager == null) {
  1154. throw new Exception(errorMessage, new Throwable("couldn't get ConnectivityManager system service"));
  1155. }
  1156. try {
  1157. // Hidden API:
  1158. //
  1159. // - Only available in Android 4.0+
  1160. // - No guarantee will be available beyond 4.2, or on all vendor
  1161. // devices
  1162. // - Field reports indicate this is no longer working on some --
  1163. // but not all -- Android 10+ devices
  1164. Class<?> LinkPropertiesClass = Class.forName("android.net.LinkProperties");
  1165. Method getActiveLinkPropertiesMethod = ConnectivityManager.class.getMethod("getActiveLinkProperties", new Class []{});
  1166. Object linkProperties = getActiveLinkPropertiesMethod.invoke(connectivityManager);
  1167. if (linkProperties != null) {
  1168. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
  1169. Method getDnsesMethod = LinkPropertiesClass.getMethod("getDnses", new Class []{});
  1170. Collection<?> dnses = (Collection<?>)getDnsesMethod.invoke(linkProperties);
  1171. for (Object dns : dnses) {
  1172. dnsAddresses.add((InetAddress)dns);
  1173. }
  1174. } else {
  1175. // LinkProperties is public in API 21 (and the DNS function signature has changed)
  1176. for (InetAddress dns : ((LinkProperties)linkProperties).getDnsServers()) {
  1177. dnsAddresses.add(dns);
  1178. }
  1179. }
  1180. }
  1181. } catch (ClassNotFoundException e) {
  1182. } catch (NoSuchMethodException e) {
  1183. } catch (IllegalArgumentException e) {
  1184. } catch (IllegalAccessException e) {
  1185. } catch (InvocationTargetException e) {
  1186. } catch (NullPointerException e) {
  1187. }
  1188. if (!dnsAddresses.isEmpty()) {
  1189. return dnsAddresses;
  1190. }
  1191. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  1192. // This case is attempted only when the hidden API fails:
  1193. //
  1194. // - Testing shows the hidden API still works more reliably on
  1195. // some Android 11+ devices
  1196. // - Testing indicates that the NetworkRequest can sometimes
  1197. // select the wrong network
  1198. // - e.g., mobile instead of WiFi, and return the wrong DNS
  1199. // servers
  1200. // - there's currently no way to filter for the "currently
  1201. // active default data network" returned by, e.g., the
  1202. // deprecated getActiveNetworkInfo
  1203. // - we cannot add the NET_CAPABILITY_FOREGROUND capability to
  1204. // the NetworkRequest at this time due to target SDK
  1205. // constraints
  1206. NetworkRequest.Builder networkRequestBuilder = new NetworkRequest.Builder()
  1207. .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
  1208. if (isVpnMode) {
  1209. // In VPN mode, we want the DNS servers for the underlying physical network.
  1210. networkRequestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
  1211. }
  1212. NetworkRequest networkRequest = networkRequestBuilder.build();
  1213. final CountDownLatch countDownLatch = new CountDownLatch(1);
  1214. try {
  1215. ConnectivityManager.NetworkCallback networkCallback =
  1216. new ConnectivityManager.NetworkCallback() {
  1217. @Override
  1218. public void onLinkPropertiesChanged(Network network,
  1219. LinkProperties linkProperties) {
  1220. dnsAddresses.addAll(linkProperties.getDnsServers());
  1221. countDownLatch.countDown();
  1222. }
  1223. };
  1224. connectivityManager.registerNetworkCallback(networkRequest, networkCallback);
  1225. countDownLatch.await(1, TimeUnit.SECONDS);
  1226. connectivityManager.unregisterNetworkCallback(networkCallback);
  1227. } catch (RuntimeException ignored) {
  1228. // Failed to register network callback
  1229. } catch (InterruptedException e) {
  1230. Thread.currentThread().interrupt();
  1231. }
  1232. }
  1233. return dnsAddresses;
  1234. }
  1235. private static boolean hasIPv6Route(Context context) throws Exception {
  1236. try {
  1237. // This logic mirrors the logic in
  1238. // psiphon/common/resolver.hasRoutableIPv6Interface. That
  1239. // function currently doesn't work on Android due to Go's
  1240. // net.InterfaceAddrs failing on Android SDK 30+ (see Go issue
  1241. // 40569). hasIPv6Route provides the same functionality via a
  1242. // callback into Java code.
  1243. for (NetworkInterface netInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
  1244. if (netInterface.isUp() &&
  1245. !netInterface.isLoopback() &&
  1246. !netInterface.isPointToPoint()) {
  1247. for (InetAddress address : Collections.list(netInterface.getInetAddresses())) {
  1248. // Per https://developer.android.com/reference/java/net/Inet6Address#textual-representation-of-ip-addresses,
  1249. // "Java will never return an IPv4-mapped address.
  1250. // These classes can take an IPv4-mapped address as
  1251. // input, both in byte array and text
  1252. // representation. However, it will be converted
  1253. // into an IPv4 address." As such, when the type of
  1254. // the IP address is Inet6Address, this should be
  1255. // an actual IPv6 address.
  1256. if (address instanceof Inet6Address &&
  1257. !address.isLinkLocalAddress() &&
  1258. !address.isSiteLocalAddress() &&
  1259. !address.isMulticastAddress ()) {
  1260. return true;
  1261. }
  1262. }
  1263. }
  1264. }
  1265. } catch (SocketException e) {
  1266. throw new Exception("hasIPv6Route failed", e);
  1267. }
  1268. return false;
  1269. }
  1270. //----------------------------------------------------------------------------------------------
  1271. // Exception
  1272. //----------------------------------------------------------------------------------------------
  1273. public static class Exception extends java.lang.Exception {
  1274. private static final long serialVersionUID = 1L;
  1275. public Exception(String message) {
  1276. super(message);
  1277. }
  1278. public Exception(String message, Throwable cause) {
  1279. super(message + ": " + cause.getMessage());
  1280. }
  1281. }
  1282. //----------------------------------------------------------------------------------------------
  1283. // Network connectivity monitor
  1284. //----------------------------------------------------------------------------------------------
  1285. private static class NetworkMonitor {
  1286. private final NetworkChangeListener listener;
  1287. private ConnectivityManager.NetworkCallback networkCallback;
  1288. public NetworkMonitor(
  1289. NetworkChangeListener listener) {
  1290. this.listener = listener;
  1291. }
  1292. private void start(Context context) throws InterruptedException {
  1293. final CountDownLatch setNetworkPropertiesCountDownLatch = new CountDownLatch(1);
  1294. // Need API 21(LOLLIPOP)+ for ConnectivityManager.NetworkCallback
  1295. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
  1296. return;
  1297. }
  1298. ConnectivityManager connectivityManager =
  1299. (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  1300. if (connectivityManager == null) {
  1301. return;
  1302. }
  1303. networkCallback = new ConnectivityManager.NetworkCallback() {
  1304. private boolean isInitialState = true;
  1305. private Network currentActiveNetwork;
  1306. private void consumeActiveNetwork(Network network) {
  1307. if (isInitialState) {
  1308. isInitialState = false;
  1309. setCurrentActiveNetworkAndProperties(network);
  1310. return;
  1311. }
  1312. if (!network.equals(currentActiveNetwork)) {
  1313. setCurrentActiveNetworkAndProperties(network);
  1314. if (listener != null) {
  1315. listener.onChanged();
  1316. }
  1317. }
  1318. }
  1319. private void consumeLostNetwork(Network network) {
  1320. if (network.equals(currentActiveNetwork)) {
  1321. setCurrentActiveNetworkAndProperties(null);
  1322. if (listener != null) {
  1323. listener.onChanged();
  1324. }
  1325. }
  1326. }
  1327. private void setCurrentActiveNetworkAndProperties(Network network) {
  1328. currentActiveNetwork = network;
  1329. if (network == null) {
  1330. mPsiphonTunnel.mActiveNetworkType.set("NONE");
  1331. mPsiphonTunnel.mActiveNetworkDNSServers.set("");
  1332. mPsiphonTunnel.mHostService.onDiagnosticMessage("NetworkMonitor: clear current active network");
  1333. } else {
  1334. String networkType = "UNKNOWN";
  1335. try {
  1336. // Limitation: a network may have both CELLULAR
  1337. // and WIFI transports, or different network
  1338. // transport types entirely. This logic currently
  1339. // mimics the type determination logic in
  1340. // getNetworkID.
  1341. NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
  1342. if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
  1343. networkType = "MOBILE";
  1344. } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
  1345. networkType = "WIFI";
  1346. }
  1347. } catch (java.lang.Exception e) {
  1348. }
  1349. mPsiphonTunnel.mActiveNetworkType.set(networkType);
  1350. ArrayList<String> servers = new ArrayList<String>();
  1351. try {
  1352. LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
  1353. List<InetAddress> serverAddresses = linkProperties.getDnsServers();
  1354. for (InetAddress serverAddress : serverAddresses) {
  1355. String server = serverAddress.toString();
  1356. if (server.startsWith("/")) {
  1357. server = server.substring(1);
  1358. }
  1359. servers.add(server);
  1360. }
  1361. } catch (java.lang.Exception e) {
  1362. }
  1363. // Use the workaround, comma-delimited format required for gobind.
  1364. mPsiphonTunnel.mActiveNetworkDNSServers.set(TextUtils.join(",", servers));
  1365. String message = "NetworkMonitor: set current active network " + networkType;
  1366. if (!servers.isEmpty()) {
  1367. // The DNS server address is potential PII and not logged.
  1368. message += " with DNS";
  1369. }
  1370. mPsiphonTunnel.mHostService.onDiagnosticMessage(message);
  1371. }
  1372. setNetworkPropertiesCountDownLatch.countDown();
  1373. }
  1374. @Override
  1375. public void onCapabilitiesChanged(Network network, NetworkCapabilities capabilities) {
  1376. super.onCapabilitiesChanged(network, capabilities);
  1377. // Need API 23(M)+ for NET_CAPABILITY_VALIDATED
  1378. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
  1379. return;
  1380. }
  1381. // https://developer.android.com/reference/android/net/NetworkCapabilities#NET_CAPABILITY_VALIDATED
  1382. // Indicates that connectivity on this network was successfully validated.
  1383. // For example, for a network with NET_CAPABILITY_INTERNET, it means that Internet connectivity was
  1384. // successfully detected.
  1385. if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
  1386. consumeActiveNetwork(network);
  1387. }
  1388. }
  1389. @Override
  1390. public void onAvailable(Network network) {
  1391. super.onAvailable(network);
  1392. // Skip on API 26(O)+ because onAvailable is guaranteed to be followed by
  1393. // onCapabilitiesChanged
  1394. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  1395. return;
  1396. }
  1397. consumeActiveNetwork(network);
  1398. }
  1399. @Override
  1400. public void onLost(Network network) {
  1401. super.onLost(network);
  1402. consumeLostNetwork(network);
  1403. }
  1404. };
  1405. try {
  1406. // When searching for a network to satisfy a request, all capabilities requested must be satisfied.
  1407. NetworkRequest.Builder builder = new NetworkRequest.Builder()
  1408. // Indicates that this network should be able to reach the internet.
  1409. .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
  1410. if (mPsiphonTunnel.mVpnMode.get()) {
  1411. // If we are in the VPN mode then ensure we monitor only the VPN's underlying
  1412. // active networks and not self.
  1413. builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
  1414. } else {
  1415. // If we are NOT in the VPN mode then monitor default active networks with the
  1416. // Internet capability, including VPN, to ensure we won't trigger a reconnect in
  1417. // case the VPN is up while the system switches the underlying network.
  1418. builder.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
  1419. }
  1420. NetworkRequest networkRequest = builder.build();
  1421. // We are using requestNetwork and not registerNetworkCallback here because we found
  1422. // that the callbacks from requestNetwork are more accurate in terms of tracking
  1423. // currently active network. Another alternative to use for tracking active network
  1424. // would be registerDefaultNetworkCallback but a) it needs API >= 24 and b) doesn't
  1425. // provide a way to set up monitoring of underlying networks only when VPN transport
  1426. // is also active.
  1427. connectivityManager.requestNetwork(networkRequest, networkCallback);
  1428. } catch (RuntimeException ignored) {
  1429. // Could be a security exception or any other runtime exception on customized firmwares.
  1430. networkCallback = null;
  1431. }
  1432. // We are going to wait up to one second for the network callback to populate
  1433. // active network properties before returning.
  1434. setNetworkPropertiesCountDownLatch.await(1, TimeUnit.SECONDS);
  1435. }
  1436. private void stop(Context context) {
  1437. if (networkCallback == null) {
  1438. return;
  1439. }
  1440. // Need API 21(LOLLIPOP)+ for ConnectivityManager.NetworkCallback
  1441. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
  1442. return;
  1443. }
  1444. ConnectivityManager connectivityManager =
  1445. (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  1446. if (connectivityManager == null) {
  1447. return;
  1448. }
  1449. // Note: ConnectivityManager.unregisterNetworkCallback() may throw
  1450. // "java.lang.IllegalArgumentException: NetworkCallback was not registered".
  1451. // This scenario should be handled in the start() above but we'll add a try/catch
  1452. // anyway to match the start's call to ConnectivityManager.registerNetworkCallback()
  1453. try {
  1454. connectivityManager.unregisterNetworkCallback(networkCallback);
  1455. } catch (RuntimeException ignored) {
  1456. }
  1457. networkCallback = null;
  1458. }
  1459. public interface NetworkChangeListener {
  1460. void onChanged();
  1461. }
  1462. }
  1463. }