PsiphonTunnel.java 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  1. /*
  2. * Copyright (c) 2024, 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.content.Context;
  21. import android.net.ConnectivityManager;
  22. import android.net.LinkProperties;
  23. import android.net.Network;
  24. import android.net.NetworkCapabilities;
  25. import android.net.NetworkInfo;
  26. import android.net.NetworkRequest;
  27. import android.net.VpnService;
  28. import android.net.wifi.WifiInfo;
  29. import android.net.wifi.WifiManager;
  30. import android.os.Build;
  31. import android.telephony.TelephonyManager;
  32. import android.text.TextUtils;
  33. import org.json.JSONArray;
  34. import org.json.JSONException;
  35. import org.json.JSONObject;
  36. import java.io.File;
  37. import java.lang.reflect.InvocationTargetException;
  38. import java.lang.reflect.Method;
  39. import java.net.Inet6Address;
  40. import java.net.InetAddress;
  41. import java.net.NetworkInterface;
  42. import java.net.SocketException;
  43. import java.util.ArrayList;
  44. import java.util.Collection;
  45. import java.util.Collections;
  46. import java.util.List;
  47. import java.util.Locale;
  48. import java.util.concurrent.CountDownLatch;
  49. import java.util.concurrent.ExecutorService;
  50. import java.util.concurrent.Executors;
  51. import java.util.concurrent.RejectedExecutionException;
  52. import java.util.concurrent.TimeUnit;
  53. import java.util.concurrent.atomic.AtomicBoolean;
  54. import java.util.concurrent.atomic.AtomicInteger;
  55. import java.util.concurrent.atomic.AtomicReference;
  56. import psi.Psi;
  57. import psi.PsiphonProvider;
  58. import psi.PsiphonProviderFeedbackHandler;
  59. import psi.PsiphonProviderNetwork;
  60. import psi.PsiphonProviderNoticeHandler;
  61. public class PsiphonTunnel {
  62. public interface HostLogger {
  63. default void onDiagnosticMessage(String message) {}
  64. }
  65. // Protocol used to communicate the outcome of feedback upload operations to the application
  66. // using PsiphonTunnelFeedback.
  67. public interface HostFeedbackHandler {
  68. // Callback which is invoked once the feedback upload has completed.
  69. // If the exception is non-null, then the upload failed.
  70. default void sendFeedbackCompleted(java.lang.Exception e) {}
  71. }
  72. public interface HostLibraryLoader {
  73. default void loadLibrary(String library) {
  74. System.loadLibrary(library);
  75. }
  76. }
  77. public interface HostService extends HostLogger, HostLibraryLoader {
  78. Context getContext();
  79. String getPsiphonConfig();
  80. default void bindToDevice(long fileDescriptor) throws Exception {
  81. throw new IllegalStateException("bindToDevice not implemented");
  82. }
  83. // Tunnel core notice handler callbacks
  84. default void onAvailableEgressRegions(List<String> regions) {}
  85. default void onSocksProxyPortInUse(int port) {}
  86. default void onHttpProxyPortInUse(int port) {}
  87. default void onListeningSocksProxyPort(int port) {}
  88. default void onListeningHttpProxyPort(int port) {}
  89. default void onUpstreamProxyError(String message) {}
  90. default void onConnecting() {}
  91. default void onConnected() {}
  92. default void onHomepage(String url) {}
  93. default void onClientRegion(String region) {}
  94. default void onClientAddress(String address) {}
  95. default void onClientUpgradeDownloaded(String filename) {}
  96. default void onClientIsLatestVersion() {}
  97. default void onSplitTunnelRegions(List<String> regions) {}
  98. default void onUntunneledAddress(String address) {}
  99. /**
  100. * Called to report how many bytes have been transferred since the last time
  101. * this function was called.
  102. * By default onBytesTransferred is disabled. Enable it by setting
  103. * EmitBytesTransferred to true in the Psiphon config.
  104. * @param sent The number of bytes sent since the last call to onBytesTransferred.
  105. * @param received The number of bytes received since the last call to onBytesTransferred.
  106. */
  107. default void onBytesTransferred(long sent, long received) {}
  108. default void onStartedWaitingForNetworkConnectivity() {}
  109. default void onStoppedWaitingForNetworkConnectivity() {}
  110. default void onActiveAuthorizationIDs(List<String> authorizations) {}
  111. default void onTrafficRateLimits(long upstreamBytesPerSecond, long downstreamBytesPerSecond) {}
  112. default void onApplicationParameters(Object parameters) {}
  113. default void onServerAlert(String reason, String subject, List<String> actionURLs) {}
  114. /**
  115. * Called when tunnel-core reports that a selected in-proxy mode --
  116. * including running a proxy; or running a client in personal pairing
  117. * mode -- cannot function without an app upgrade. The receiver
  118. * should alert the user to upgrade the app and/or disable the
  119. * unsupported mode(s). This callback is followed by a tunnel-core
  120. * shutdown.
  121. */
  122. default void onInproxyMustUpgrade() {}
  123. /**
  124. * Called when tunnel-core reports proxy usage statistics.
  125. * By default onInproxyProxyActivity is disabled. Enable it by setting
  126. * EmitInproxyProxyActivity to true in the Psiphon config.
  127. * @param connectingClients Number of clients connecting to the proxy.
  128. * @param connectedClients Number of clients currently connected to the proxy.
  129. * @param bytesUp Bytes uploaded through the proxy since the last report.
  130. * @param bytesDown Bytes downloaded through the proxy since the last report.
  131. */
  132. default void onInproxyProxyActivity(int connectingClients, int connectedClients,long bytesUp, long bytesDown) {}
  133. /**
  134. * Called when tunnel-core reports connected server region information.
  135. * @param region The server region received.
  136. */
  137. default void onConnectedServerRegion(String region) {}
  138. default void onExiting() {}
  139. }
  140. private final HostService mHostService;
  141. private final AtomicBoolean mVpnMode;
  142. private final AtomicInteger mLocalSocksProxyPort;
  143. private final AtomicBoolean mIsWaitingForNetworkConnectivity;
  144. private final AtomicReference<String> mClientPlatformPrefix;
  145. private final AtomicReference<String> mClientPlatformSuffix;
  146. private final NetworkMonitor mNetworkMonitor;
  147. private final AtomicReference<String> mActiveNetworkType;
  148. private final AtomicReference<String> mActiveNetworkDNSServers;
  149. // Only one PsiphonTunnel instance may exist at a time, as the underlying psi.Psi contains
  150. // global state.
  151. private static PsiphonTunnel INSTANCE = null;
  152. public static synchronized PsiphonTunnel newPsiphonTunnel(HostService hostService) {
  153. if (INSTANCE != null) {
  154. INSTANCE.stop();
  155. }
  156. INSTANCE = new PsiphonTunnel(hostService);
  157. return INSTANCE;
  158. }
  159. public void setVpnMode(boolean isVpnMode) {
  160. this.mVpnMode.set(isVpnMode);
  161. }
  162. // Returns default path where upgrade downloads will be paved. Only applicable if
  163. // DataRootDirectory was not set in the outer config. If DataRootDirectory was set in the
  164. // outer config, use getUpgradeDownloadFilePath with its value instead.
  165. public static String getDefaultUpgradeDownloadFilePath(Context context) {
  166. return Psi.upgradeDownloadFilePath(defaultDataRootDirectory(context).getAbsolutePath());
  167. }
  168. // Returns the path where upgrade downloads will be paved relative to the configured
  169. // DataRootDirectory.
  170. public static String getUpgradeDownloadFilePath(String dataRootDirectoryPath) {
  171. return Psi.upgradeDownloadFilePath(dataRootDirectoryPath);
  172. }
  173. private static File defaultDataRootDirectory(Context context) {
  174. return context.getFileStreamPath("ca.psiphon.PsiphonTunnel.tunnel-core");
  175. }
  176. private PsiphonTunnel(HostService hostService) {
  177. // Load the native go code embedded in psi.aar
  178. hostService.loadLibrary("gojni");
  179. mHostService = hostService;
  180. mVpnMode = new AtomicBoolean(false);
  181. mLocalSocksProxyPort = new AtomicInteger(0);
  182. mIsWaitingForNetworkConnectivity = new AtomicBoolean(false);
  183. mClientPlatformPrefix = new AtomicReference<>("");
  184. mClientPlatformSuffix = new AtomicReference<>("");
  185. mActiveNetworkType = new AtomicReference<>("");
  186. mActiveNetworkDNSServers = new AtomicReference<>("");
  187. mNetworkMonitor = new NetworkMonitor(new NetworkMonitor.NetworkChangeListener() {
  188. @Override
  189. public void onChanged() {
  190. try {
  191. reconnectPsiphon();
  192. } catch (Exception e) {
  193. mHostService.onDiagnosticMessage("reconnect error: " + e);
  194. }
  195. }
  196. });
  197. }
  198. public Object clone() throws CloneNotSupportedException {
  199. throw new CloneNotSupportedException();
  200. }
  201. //----------------------------------------------------------------------------------------------
  202. // Public API
  203. //----------------------------------------------------------------------------------------------
  204. // Throws an exception if start fails. The caller may examine the exception message
  205. // to determine the cause of the error.
  206. public synchronized void startTunneling(String embeddedServerEntries) throws Exception {
  207. startPsiphon(embeddedServerEntries);
  208. }
  209. // Note: to avoid deadlock, do not call directly from a HostService callback;
  210. // instead post to a Handler if necessary to trigger from a HostService callback.
  211. // For example, deadlock can occur when a Notice callback invokes stop() since stop() calls
  212. // Psi.stop() which will block waiting for tunnel-core Controller to shutdown which in turn
  213. // waits for Notice callback invoker to stop, meanwhile the callback thread has blocked waiting
  214. // for stop().
  215. public synchronized void stop() {
  216. stopPsiphon();
  217. mVpnMode.set(false);
  218. mLocalSocksProxyPort.set(0);
  219. }
  220. // Note: same deadlock note as stop().
  221. public synchronized void restartPsiphon() throws Exception {
  222. stopPsiphon();
  223. startPsiphon("");
  224. }
  225. public synchronized void reconnectPsiphon() throws Exception {
  226. Psi.reconnectTunnel();
  227. }
  228. public void setClientPlatformAffixes(String prefix, String suffix) {
  229. mClientPlatformPrefix.set(prefix);
  230. mClientPlatformSuffix.set(suffix);
  231. }
  232. public String exportExchangePayload() {
  233. return Psi.exportExchangePayload();
  234. }
  235. public boolean importExchangePayload(String payload) {
  236. return Psi.importExchangePayload(payload);
  237. }
  238. // Writes Go runtime profile information to a set of files in the specifiec output directory.
  239. // cpuSampleDurationSeconds and blockSampleDurationSeconds determines how to long to wait and
  240. // sample profiles that require active sampling. When set to 0, these profiles are skipped.
  241. public void writeRuntimeProfiles(String outputDirectory, int cpuSampleDurationSeconds, int blockSampleDurationSeconds) {
  242. Psi.writeRuntimeProfiles(outputDirectory, cpuSampleDurationSeconds, blockSampleDurationSeconds);
  243. }
  244. // The interface for managing the Psiphon feedback upload operations.
  245. // Warnings:
  246. // - Should not be used in the same process as PsiphonTunnel.
  247. // - Only a single instance of PsiphonTunnelFeedback should be used at a time. Using multiple
  248. // instances in parallel, or concurrently, will result in undefined behavior.
  249. public static class PsiphonTunnelFeedback {
  250. private final ExecutorService workQueue = Executors.newSingleThreadExecutor();
  251. private final ExecutorService callbackQueue = Executors.newSingleThreadExecutor();
  252. void shutdownAndAwaitTermination(ExecutorService pool) {
  253. try {
  254. // Wait a while for existing tasks to terminate
  255. if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
  256. pool.shutdownNow(); // Cancel currently executing tasks
  257. // Wait a while for tasks to respond to being cancelled
  258. if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
  259. System.err.println("PsiphonTunnelFeedback: pool did not terminate");
  260. }
  261. }
  262. } catch (InterruptedException ie) {
  263. // (Re-)Cancel if current thread also interrupted
  264. pool.shutdownNow();
  265. // Preserve interrupt status
  266. Thread.currentThread().interrupt();
  267. }
  268. }
  269. // Upload a feedback package to Psiphon Inc. The app collects feedback and diagnostics
  270. // information in a particular format, then calls this function to upload it for later
  271. // investigation. The feedback compatible config and upload path must be provided by
  272. // Psiphon Inc. This call is asynchronous and returns before the upload completes. The
  273. // operation has completed when sendFeedbackCompleted() is called on the provided
  274. // HostFeedbackHandler. The provided HostLogger will be called to log informational notices,
  275. // including warnings.
  276. //
  277. // Warnings:
  278. // - Only one active upload is supported at a time. An ongoing upload will be cancelled if
  279. // this function is called again before it completes.
  280. // - An ongoing feedback upload started with startSendFeedback() should be stopped with
  281. // stopSendFeedback() before the process exits. This ensures that any underlying resources
  282. // are cleaned up; failing to do so may result in data store corruption or other undefined
  283. // behavior.
  284. // - PsiphonTunnel.startTunneling and startSendFeedback both make an attempt to migrate
  285. // persistent files from legacy locations in a one-time operation. If these functions are
  286. // called in parallel, then there is a chance that the migration attempts could execute at
  287. // the same time and result in non-fatal errors in one, or both, of the migration
  288. // operations.
  289. public void startSendFeedback(Context context, HostFeedbackHandler feedbackHandler, HostLogger logger,
  290. String feedbackConfigJson, String diagnosticsJson, String uploadPath,
  291. String clientPlatformPrefix, String clientPlatformSuffix) {
  292. workQueue.execute(new Runnable() {
  293. @Override
  294. public void run() {
  295. try {
  296. // Adds fields used in feedback upload, e.g. client platform.
  297. String psiphonConfig = buildPsiphonConfig(context, feedbackConfigJson,
  298. clientPlatformPrefix, clientPlatformSuffix, 0);
  299. Psi.startSendFeedback(psiphonConfig, diagnosticsJson, uploadPath,
  300. new PsiphonProviderFeedbackHandler() {
  301. @Override
  302. public void sendFeedbackCompleted(java.lang.Exception e) {
  303. try {
  304. callbackQueue.execute(new Runnable() {
  305. @Override
  306. public void run() {
  307. feedbackHandler.sendFeedbackCompleted(e);
  308. }
  309. });
  310. } catch (RejectedExecutionException ignored) {
  311. }
  312. }
  313. },
  314. new PsiphonProviderNetwork() {
  315. @Override
  316. public long hasNetworkConnectivity() {
  317. boolean hasConnectivity = PsiphonTunnel.hasNetworkConnectivity(context);
  318. // TODO: change to bool return value once gobind supports that type
  319. return hasConnectivity ? 1 : 0;
  320. }
  321. @Override
  322. public String getNetworkID() {
  323. // startSendFeedback is invoked from the Psiphon UI process, not the Psiphon
  324. // VPN process.
  325. //
  326. // Case 1: no VPN is running
  327. //
  328. // isVpnMode = true/false doesn't change the network ID; the network ID will
  329. // be the physical network ID, and feedback may load existing tactics or may
  330. // fetch tactics.
  331. //
  332. // Case 2: Psiphon VPN is running
  333. //
  334. // In principle, we might want to set isVpnMode = true so that we obtain the
  335. // physical network ID and load any existing tactics. However, as the VPN
  336. // holds a lock on the data store, the load will fail; also no tactics request
  337. // is attempted.
  338. //
  339. // Hypothetically, if a tactics request did proceed, the tunneled client GeoIP
  340. // would not reflect the actual client location, and so it's safer to set
  341. // isVpnMode = false to ensure fetched tactics are stored under a distinct
  342. // Network ID ("VPN").
  343. //
  344. // Case 3: another VPN is running
  345. //
  346. // Unlike case 2, there's no Psiphon VPN process holding the data store lock.
  347. // As with case 2, there's some merit to setting isVpnMode = true in order to
  348. // load existing tactics, but since a tactics request may proceed, it's safer
  349. // to set isVpnMode = false and store fetched tactics under a distinct
  350. // Network ID ("VPN").
  351. return PsiphonTunnel.getNetworkID(context, false);
  352. }
  353. @Override
  354. public String iPv6Synthesize(String IPv4Addr) {
  355. // Unused on Android.
  356. return PsiphonTunnel.iPv6Synthesize(IPv4Addr);
  357. }
  358. @Override
  359. public long hasIPv6Route() {
  360. return PsiphonTunnel.hasIPv6Route(context, logger);
  361. }
  362. },
  363. new PsiphonProviderNoticeHandler() {
  364. @Override
  365. public void notice(String noticeJSON) {
  366. try {
  367. JSONObject notice = new JSONObject(noticeJSON);
  368. String noticeType = notice.getString("noticeType");
  369. JSONObject data = notice.getJSONObject("data");
  370. String diagnosticMessage = noticeType + ": " + data;
  371. try {
  372. callbackQueue.execute(new Runnable() {
  373. @Override
  374. public void run() {
  375. logger.onDiagnosticMessage(diagnosticMessage);
  376. }
  377. });
  378. } catch (RejectedExecutionException ignored) {
  379. }
  380. } catch (java.lang.Exception e) {
  381. try {
  382. callbackQueue.execute(new Runnable() {
  383. @Override
  384. public void run() {
  385. logger.onDiagnosticMessage("Error handling notice " + e);
  386. }
  387. });
  388. } catch (RejectedExecutionException ignored) {
  389. }
  390. }
  391. }
  392. },
  393. false, // Do not use IPv6 synthesizer for Android
  394. true // Use hasIPv6Route on Android
  395. );
  396. } catch (java.lang.Exception e) {
  397. try {
  398. callbackQueue.execute(new Runnable() {
  399. @Override
  400. public void run() {
  401. feedbackHandler.sendFeedbackCompleted(new Exception("Error sending feedback", e));
  402. }
  403. });
  404. } catch (RejectedExecutionException ignored) {
  405. }
  406. }
  407. }
  408. });
  409. }
  410. // Interrupt an in-progress feedback upload operation started with startSendFeedback() and shutdown
  411. // executor queues.
  412. // NOTE: this instance cannot be reused after shutdown() has been called.
  413. public void shutdown() {
  414. workQueue.execute(new Runnable() {
  415. @Override
  416. public void run() {
  417. Psi.stopSendFeedback();
  418. }
  419. });
  420. shutdownAndAwaitTermination(workQueue);
  421. shutdownAndAwaitTermination(callbackQueue);
  422. }
  423. }
  424. private boolean isVpnMode() {
  425. return mVpnMode.get();
  426. }
  427. private void setLocalSocksProxyPort(int port) {
  428. mLocalSocksProxyPort.set(port);
  429. }
  430. public int getLocalSocksProxyPort() {
  431. return mLocalSocksProxyPort.get();
  432. }
  433. //----------------------------------------------------------------------------------------------
  434. // PsiphonProvider (Core support) interface implementation
  435. //----------------------------------------------------------------------------------------------
  436. // The PsiphonProvider functions are called from Go, and must be public to be accessible
  437. // via the gobind mechanim. To avoid making internal implementation functions public,
  438. // PsiphonProviderShim is used as a wrapper.
  439. private class PsiphonProviderShim implements PsiphonProvider {
  440. private final PsiphonTunnel mPsiphonTunnel;
  441. public PsiphonProviderShim(PsiphonTunnel psiphonTunnel) {
  442. mPsiphonTunnel = psiphonTunnel;
  443. }
  444. @Override
  445. public void notice(String noticeJSON) {
  446. mPsiphonTunnel.notice(noticeJSON);
  447. }
  448. @Override
  449. public String bindToDevice(long fileDescriptor) throws Exception {
  450. return mPsiphonTunnel.bindToDevice(fileDescriptor);
  451. }
  452. @Override
  453. public long hasNetworkConnectivity() {
  454. return mPsiphonTunnel.hasNetworkConnectivity();
  455. }
  456. @Override
  457. public String getDNSServersAsString() {
  458. return mPsiphonTunnel.getDNSServers(mHostService.getContext(), mHostService);
  459. }
  460. @Override
  461. public String iPv6Synthesize(String IPv4Addr) {
  462. return PsiphonTunnel.iPv6Synthesize(IPv4Addr);
  463. }
  464. @Override
  465. public long hasIPv6Route() {
  466. return PsiphonTunnel.hasIPv6Route(mHostService.getContext(), mHostService);
  467. }
  468. @Override
  469. public String getNetworkID() {
  470. return PsiphonTunnel.getNetworkID(mHostService.getContext(), mPsiphonTunnel.isVpnMode());
  471. }
  472. }
  473. private void notice(String noticeJSON) {
  474. handlePsiphonNotice(noticeJSON);
  475. }
  476. private String bindToDevice(long fileDescriptor) throws Exception {
  477. mHostService.bindToDevice(fileDescriptor);
  478. return "";
  479. }
  480. private long hasNetworkConnectivity() {
  481. boolean hasConnectivity = hasNetworkConnectivity(mHostService.getContext());
  482. boolean wasWaitingForNetworkConnectivity = mIsWaitingForNetworkConnectivity.getAndSet(!hasConnectivity);
  483. // HasNetworkConnectivity may be called many times, but only invoke
  484. // callbacks once per loss or resumption of connectivity, so, e.g.,
  485. // the HostService may log a single message.
  486. if (!hasConnectivity && !wasWaitingForNetworkConnectivity) {
  487. mHostService.onStartedWaitingForNetworkConnectivity();
  488. } else if (hasConnectivity && wasWaitingForNetworkConnectivity) {
  489. mHostService.onStoppedWaitingForNetworkConnectivity();
  490. }
  491. // TODO: change to bool return value once gobind supports that type
  492. return hasConnectivity ? 1 : 0;
  493. }
  494. private String getDNSServers(Context context, HostLogger logger) {
  495. // Use the DNS servers set by mNetworkMonitor,
  496. // mActiveNetworkDNSServers, when available. It's the most reliable
  497. // mechanism. Otherwise fallback to getActiveNetworkDNSServers.
  498. //
  499. // mActiveNetworkDNSServers is not available on API < 21
  500. // (LOLLIPOP). mActiveNetworkDNSServers may also be temporarily
  501. // unavailable if the last active network has been lost and no new
  502. // one has yet replaced it.
  503. String servers = mActiveNetworkDNSServers.get();
  504. if (servers != "") {
  505. return servers;
  506. }
  507. try {
  508. // Use the workaround, comma-delimited format required for gobind.
  509. servers = TextUtils.join(",", getActiveNetworkDNSServers(context, mVpnMode.get()));
  510. } catch (Exception e) {
  511. logger.onDiagnosticMessage("failed to get active network DNS resolver: " + e.getMessage());
  512. // Alternate DNS servers will be provided by psiphon-tunnel-core
  513. // config or tactics.
  514. }
  515. return servers;
  516. }
  517. private static String iPv6Synthesize(String IPv4Addr) {
  518. // Unused on Android.
  519. return IPv4Addr;
  520. }
  521. private static long hasIPv6Route(Context context, HostLogger logger) {
  522. boolean hasRoute = false;
  523. try {
  524. hasRoute = hasIPv6Route(context);
  525. } catch (Exception e) {
  526. logger.onDiagnosticMessage("failed to check IPv6 route: " + e.getMessage());
  527. }
  528. // TODO: change to bool return value once gobind supports that type
  529. return hasRoute ? 1 : 0;
  530. }
  531. private static String getNetworkID(Context context, boolean isVpnMode) {
  532. // TODO: getActiveNetworkInfo is deprecated in API 29; once
  533. // getActiveNetworkInfo is no longer available, use
  534. // mActiveNetworkType which is updated by mNetworkMonitor.
  535. // The network ID contains potential PII. In tunnel-core, the network ID
  536. // is used only locally in the client and not sent to the server.
  537. //
  538. // See network ID requirements here:
  539. // https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter
  540. String networkID = "UNKNOWN";
  541. ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  542. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  543. if (!isVpnMode) {
  544. NetworkCapabilities capabilities = null;
  545. try {
  546. Network nw = connectivityManager.getActiveNetwork();
  547. capabilities = connectivityManager.getNetworkCapabilities(nw);
  548. } catch (java.lang.Exception e) {
  549. // May get exceptions due to missing permissions like android.permission.ACCESS_NETWORK_STATE.
  550. // Apps using the Psiphon Library and lacking android.permission.ACCESS_NETWORK_STATE will
  551. // proceed and use tactics, but with "UNKNOWN" as the sole network ID.
  552. }
  553. if (capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
  554. return "VPN";
  555. }
  556. }
  557. }
  558. NetworkInfo activeNetworkInfo = null;
  559. try {
  560. activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
  561. } catch (java.lang.Exception e) {
  562. // May get exceptions due to missing permissions like android.permission.ACCESS_NETWORK_STATE.
  563. // Apps using the Psiphon Library and lacking android.permission.ACCESS_NETWORK_STATE will
  564. // proceed and use tactics, but with "UNKNOWN" as the sole network ID.
  565. }
  566. if (activeNetworkInfo != null && activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
  567. networkID = "WIFI";
  568. try {
  569. // Use the application context here to avoid lint warning:
  570. // "The WIFI_SERVICE must be looked up on the application context to prevent
  571. // memory leaks on devices running Android versions earlier than N."
  572. WifiManager wifiManager = (WifiManager) context.getApplicationContext()
  573. .getSystemService(Context.WIFI_SERVICE);
  574. WifiInfo wifiInfo = wifiManager.getConnectionInfo();
  575. if (wifiInfo != null) {
  576. String wifiNetworkID = wifiInfo.getBSSID();
  577. if (wifiNetworkID.equals("02:00:00:00:00:00")) {
  578. // "02:00:00:00:00:00" is reported when the app does not have the ACCESS_COARSE_LOCATION permission:
  579. // https://developer.android.com/about/versions/marshmallow/android-6.0-changes#behavior-hardware-id
  580. // The Psiphon client should allow the user to opt-in to this permission. If they decline, fail over
  581. // to using the WiFi IP address.
  582. wifiNetworkID = String.valueOf(wifiInfo.getIpAddress());
  583. }
  584. networkID += "-" + wifiNetworkID;
  585. }
  586. } catch (java.lang.Exception e) {
  587. // May get exceptions due to missing permissions like android.permission.ACCESS_WIFI_STATE.
  588. // Fall through and use just "WIFI"
  589. }
  590. } else if (activeNetworkInfo != null && activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
  591. networkID = "MOBILE";
  592. try {
  593. TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
  594. if (telephonyManager != null) {
  595. networkID += "-" + telephonyManager.getNetworkOperator();
  596. }
  597. } catch (java.lang.Exception e) {
  598. // May get exceptions due to missing permissions.
  599. // Fall through and use just "MOBILE"
  600. }
  601. }
  602. return networkID;
  603. }
  604. //----------------------------------------------------------------------------------------------
  605. // Psiphon Tunnel Core
  606. //----------------------------------------------------------------------------------------------
  607. private void startPsiphon(String embeddedServerEntries) throws Exception {
  608. stopPsiphon();
  609. mIsWaitingForNetworkConnectivity.set(false);
  610. mHostService.onDiagnosticMessage("starting Psiphon library");
  611. try {
  612. // mNetworkMonitor.start() will wait up to 1 second before returning to give the network
  613. // callback a chance to populate active network properties before we start the tunnel.
  614. mNetworkMonitor.start(mHostService.getContext());
  615. Psi.start(
  616. loadPsiphonConfig(mHostService.getContext()),
  617. embeddedServerEntries,
  618. "",
  619. new PsiphonProviderShim(this),
  620. isVpnMode(),
  621. false, // Do not use IPv6 synthesizer for Android
  622. true // Use hasIPv6Route on Android
  623. );
  624. } catch (java.lang.Exception e) {
  625. throw new Exception("failed to start Psiphon library", e);
  626. }
  627. mHostService.onDiagnosticMessage("Psiphon library started");
  628. }
  629. private void stopPsiphon() {
  630. mHostService.onDiagnosticMessage("stopping Psiphon library");
  631. mNetworkMonitor.stop(mHostService.getContext());
  632. Psi.stop();
  633. mHostService.onDiagnosticMessage("Psiphon library stopped");
  634. }
  635. private String loadPsiphonConfig(Context context)
  636. throws JSONException, Exception {
  637. return buildPsiphonConfig(context, mHostService.getPsiphonConfig(),
  638. mClientPlatformPrefix.get(), mClientPlatformSuffix.get(), mLocalSocksProxyPort.get());
  639. }
  640. private static String buildPsiphonConfig(Context context, String psiphonConfig,
  641. String clientPlatformPrefix, String clientPlatformSuffix,
  642. Integer localSocksProxyPort) throws JSONException, Exception {
  643. // Load settings from the raw resource JSON config file and
  644. // update as necessary. Then write JSON to disk for the Go client.
  645. JSONObject json = new JSONObject(psiphonConfig);
  646. // On Android, this directory must be set to the app private storage area.
  647. // The Psiphon library won't be able to use its current working directory
  648. // and the standard temporary directories do not exist.
  649. if (!json.has("DataRootDirectory")) {
  650. File dataRootDirectory = defaultDataRootDirectory(context);
  651. if (!dataRootDirectory.exists()) {
  652. boolean created = dataRootDirectory.mkdir();
  653. if (!created) {
  654. throw new Exception(
  655. "failed to create data root directory: " + dataRootDirectory.getPath());
  656. }
  657. }
  658. json.put("DataRootDirectory", defaultDataRootDirectory(context));
  659. }
  660. // Migrate datastore files from legacy directory.
  661. if (!json.has("DataStoreDirectory")) {
  662. json.put("MigrateDataStoreDirectory", context.getFilesDir());
  663. }
  664. // Migrate remote server list downloads from legacy location.
  665. if (!json.has("RemoteServerListDownloadFilename")) {
  666. File remoteServerListDownload = new File(context.getFilesDir(), "remote_server_list");
  667. json.put("MigrateRemoteServerListDownloadFilename",
  668. remoteServerListDownload.getAbsolutePath());
  669. }
  670. // Migrate obfuscated server list download files from legacy directory.
  671. File oslDownloadDir = new File(context.getFilesDir(), "osl");
  672. json.put("MigrateObfuscatedServerListDownloadDirectory", oslDownloadDir.getAbsolutePath());
  673. // Continue to run indefinitely until connected
  674. if (!json.has("EstablishTunnelTimeoutSeconds")) {
  675. json.put("EstablishTunnelTimeoutSeconds", 0);
  676. }
  677. if (localSocksProxyPort != 0 && (!json.has("LocalSocksProxyPort") || json.getInt(
  678. "LocalSocksProxyPort") == 0)) {
  679. // When mLocalSocksProxyPort is set, tun2socks is already configured
  680. // to use that port value. So we force use of the same port.
  681. // A side-effect of this is that changing the SOCKS port preference
  682. // has no effect with restartPsiphon(), a full stop() is necessary.
  683. json.put("LocalSocksProxyPort", localSocksProxyPort);
  684. }
  685. json.put("DeviceRegion", getDeviceRegion(context));
  686. StringBuilder clientPlatform = new StringBuilder();
  687. if (clientPlatformPrefix.length() > 0) {
  688. clientPlatform.append(clientPlatformPrefix);
  689. }
  690. clientPlatform.append("Android_");
  691. clientPlatform.append(Build.VERSION.RELEASE);
  692. clientPlatform.append("_");
  693. clientPlatform.append(context.getPackageName());
  694. if (clientPlatformSuffix.length() > 0) {
  695. clientPlatform.append(clientPlatformSuffix);
  696. }
  697. json.put("ClientPlatform", clientPlatform.toString().replaceAll("[^\\w\\-\\.]", "_"));
  698. return json.toString();
  699. }
  700. private void handlePsiphonNotice(String noticeJSON) {
  701. try {
  702. // All notices are sent on as diagnostic messages
  703. // except those that may contain private user data.
  704. boolean diagnostic = true;
  705. JSONObject notice = new JSONObject(noticeJSON);
  706. String noticeType = notice.getString("noticeType");
  707. if (noticeType.equals("Tunnels")) {
  708. int count = notice.getJSONObject("data").getInt("count");
  709. if (count == 0) {
  710. mHostService.onConnecting();
  711. } else if (count == 1) {
  712. mHostService.onConnected();
  713. }
  714. // count > 1 is an additional multi-tunnel establishment, and not reported.
  715. } else if (noticeType.equals("AvailableEgressRegions")) {
  716. JSONArray egressRegions = notice.getJSONObject("data").getJSONArray("regions");
  717. ArrayList<String> regions = new ArrayList<>();
  718. for (int i=0; i<egressRegions.length(); i++) {
  719. regions.add(egressRegions.getString(i));
  720. }
  721. mHostService.onAvailableEgressRegions(regions);
  722. } else if (noticeType.equals("SocksProxyPortInUse")) {
  723. mHostService.onSocksProxyPortInUse(notice.getJSONObject("data").getInt("port"));
  724. } else if (noticeType.equals("HttpProxyPortInUse")) {
  725. mHostService.onHttpProxyPortInUse(notice.getJSONObject("data").getInt("port"));
  726. } else if (noticeType.equals("ListeningSocksProxyPort")) {
  727. int port = notice.getJSONObject("data").getInt("port");
  728. setLocalSocksProxyPort(port);
  729. mHostService.onListeningSocksProxyPort(port);
  730. } else if (noticeType.equals("ListeningHttpProxyPort")) {
  731. int port = notice.getJSONObject("data").getInt("port");
  732. mHostService.onListeningHttpProxyPort(port);
  733. } else if (noticeType.equals("UpstreamProxyError")) {
  734. diagnostic = false;
  735. mHostService.onUpstreamProxyError(notice.getJSONObject("data").getString("message"));
  736. } else if (noticeType.equals("ClientUpgradeDownloaded")) {
  737. mHostService.onClientUpgradeDownloaded(notice.getJSONObject("data").getString("filename"));
  738. } else if (noticeType.equals("ClientIsLatestVersion")) {
  739. mHostService.onClientIsLatestVersion();
  740. } else if (noticeType.equals("Homepage")) {
  741. mHostService.onHomepage(notice.getJSONObject("data").getString("url"));
  742. } else if (noticeType.equals("ClientRegion")) {
  743. mHostService.onClientRegion(notice.getJSONObject("data").getString("region"));
  744. } else if (noticeType.equals("ClientAddress")) {
  745. diagnostic = false;
  746. mHostService.onClientAddress(notice.getJSONObject("data").getString("address"));
  747. } else if (noticeType.equals("SplitTunnelRegions")) {
  748. JSONArray splitTunnelRegions = notice.getJSONObject("data").getJSONArray("regions");
  749. ArrayList<String> regions = new ArrayList<>();
  750. for (int i=0; i<splitTunnelRegions.length(); i++) {
  751. regions.add(splitTunnelRegions.getString(i));
  752. }
  753. mHostService.onSplitTunnelRegions(regions);
  754. } else if (noticeType.equals("Untunneled")) {
  755. diagnostic = false;
  756. mHostService.onUntunneledAddress(notice.getJSONObject("data").getString("address"));
  757. } else if (noticeType.equals("BytesTransferred")) {
  758. diagnostic = false;
  759. JSONObject data = notice.getJSONObject("data");
  760. mHostService.onBytesTransferred(data.getLong("sent"), data.getLong("received"));
  761. } else if (noticeType.equals("ActiveAuthorizationIDs")) {
  762. JSONArray activeAuthorizationIDs = notice.getJSONObject("data").getJSONArray("IDs");
  763. ArrayList<String> authorizations = new ArrayList<>();
  764. for (int i=0; i<activeAuthorizationIDs.length(); i++) {
  765. authorizations.add(activeAuthorizationIDs.getString(i));
  766. }
  767. mHostService.onActiveAuthorizationIDs(authorizations);
  768. } else if (noticeType.equals("TrafficRateLimits")) {
  769. JSONObject data = notice.getJSONObject("data");
  770. mHostService.onTrafficRateLimits(
  771. data.getLong("upstreamBytesPerSecond"), data.getLong("downstreamBytesPerSecond"));
  772. } else if (noticeType.equals("Exiting")) {
  773. mHostService.onExiting();
  774. } else if (noticeType.equals("ConnectedServerRegion")) {
  775. mHostService.onConnectedServerRegion(
  776. notice.getJSONObject("data").getString("serverRegion"));
  777. } else if (noticeType.equals("ApplicationParameters")) {
  778. mHostService.onApplicationParameters(
  779. notice.getJSONObject("data").get("parameters"));
  780. } else if (noticeType.equals("ServerAlert")) {
  781. JSONArray actionURLs = notice.getJSONObject("data").getJSONArray("actionURLs");
  782. ArrayList<String> actionURLsList = new ArrayList<>();
  783. for (int i=0; i<actionURLs.length(); i++) {
  784. actionURLsList.add(actionURLs.getString(i));
  785. }
  786. mHostService.onServerAlert(
  787. notice.getJSONObject("data").getString("reason"),
  788. notice.getJSONObject("data").getString("subject"),
  789. actionURLsList);
  790. } else if (noticeType.equals("InproxyMustUpgrade")) {
  791. mHostService.onInproxyMustUpgrade();
  792. } else if (noticeType.equals("InproxyProxyActivity")) {
  793. JSONObject data = notice.getJSONObject("data");
  794. mHostService.onInproxyProxyActivity(
  795. data.getInt("connectingClients"),
  796. data.getInt("connectedClients"),
  797. data.getLong("bytesUp"),
  798. data.getLong("bytesDown"));
  799. }
  800. if (diagnostic) {
  801. String diagnosticMessage = noticeType + ": " + notice.getJSONObject("data");
  802. mHostService.onDiagnosticMessage(diagnosticMessage);
  803. }
  804. } catch (JSONException e) {
  805. // Ignore notice
  806. }
  807. }
  808. private static String getDeviceRegion(Context context) {
  809. String region = "";
  810. TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
  811. if (telephonyManager != null) {
  812. // getNetworkCountryIso, when present, is preferred over
  813. // getSimCountryIso, since getNetworkCountryIso is the network
  814. // the device is currently on, while getSimCountryIso is the home
  815. // region of the SIM. While roaming, only getNetworkCountryIso
  816. // may more accurately represent the actual device region.
  817. if (telephonyManager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
  818. region = telephonyManager.getNetworkCountryIso();
  819. if (region == null) {
  820. region = "";
  821. }
  822. }
  823. if (region.length() == 0) {
  824. region = telephonyManager.getSimCountryIso();
  825. if (region == null) {
  826. region = "";
  827. }
  828. }
  829. }
  830. if (region.length() == 0) {
  831. Locale defaultLocale = Locale.getDefault();
  832. if (defaultLocale != null) {
  833. region = defaultLocale.getCountry();
  834. }
  835. }
  836. return region.toUpperCase(Locale.US);
  837. }
  838. //----------------------------------------------------------------------------------------------
  839. // Implementation: Network Utils
  840. //----------------------------------------------------------------------------------------------
  841. private static boolean hasNetworkConnectivity(Context context) {
  842. ConnectivityManager connectivityManager =
  843. (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  844. if (connectivityManager == null) {
  845. return false;
  846. }
  847. NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
  848. return networkInfo != null && networkInfo.isConnected();
  849. }
  850. private static Collection<String> getActiveNetworkDNSServers(Context context, boolean isVpnMode)
  851. throws Exception {
  852. ArrayList<String> servers = new ArrayList<>();
  853. for (InetAddress serverAddress : getActiveNetworkDNSServerAddresses(context, isVpnMode)) {
  854. String server = serverAddress.toString();
  855. // strip the leading slash e.g., "/192.168.1.1"
  856. if (server.startsWith("/")) {
  857. server = server.substring(1);
  858. }
  859. servers.add(server);
  860. }
  861. if (servers.isEmpty()) {
  862. throw new Exception("no active network DNS resolver");
  863. }
  864. return servers;
  865. }
  866. private static Collection<InetAddress> getActiveNetworkDNSServerAddresses(Context context, boolean isVpnMode)
  867. throws Exception {
  868. final String errorMessage = "getActiveNetworkDNSServerAddresses failed";
  869. ArrayList<InetAddress> dnsAddresses = new ArrayList<>();
  870. ConnectivityManager connectivityManager =
  871. (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  872. if (connectivityManager == null) {
  873. throw new Exception(errorMessage, new Throwable("couldn't get ConnectivityManager system service"));
  874. }
  875. try {
  876. // Hidden API:
  877. //
  878. // - Only available in Android 4.0+
  879. // - No guarantee will be available beyond 4.2, or on all vendor
  880. // devices
  881. // - Field reports indicate this is no longer working on some --
  882. // but not all -- Android 10+ devices
  883. Class<?> LinkPropertiesClass = Class.forName("android.net.LinkProperties");
  884. Method getActiveLinkPropertiesMethod = ConnectivityManager.class.getMethod("getActiveLinkProperties", new Class []{});
  885. Object linkProperties = getActiveLinkPropertiesMethod.invoke(connectivityManager);
  886. if (linkProperties != null) {
  887. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
  888. Method getDnsesMethod = LinkPropertiesClass.getMethod("getDnses", new Class []{});
  889. Collection<?> dnses = (Collection<?>)getDnsesMethod.invoke(linkProperties);
  890. if (dnses != null) {
  891. for (Object dns : dnses) {
  892. dnsAddresses.add((InetAddress)dns);
  893. }
  894. }
  895. } else {
  896. // LinkProperties is public in API 21 (and the DNS function signature has changed)
  897. for (InetAddress dns : ((LinkProperties)linkProperties).getDnsServers()) {
  898. dnsAddresses.add(dns);
  899. }
  900. }
  901. }
  902. } catch (ClassNotFoundException e) {
  903. } catch (NoSuchMethodException e) {
  904. } catch (IllegalArgumentException e) {
  905. } catch (IllegalAccessException e) {
  906. } catch (InvocationTargetException e) {
  907. } catch (NullPointerException e) {
  908. }
  909. if (!dnsAddresses.isEmpty()) {
  910. return dnsAddresses;
  911. }
  912. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  913. // This case is attempted only when the hidden API fails:
  914. //
  915. // - Testing shows the hidden API still works more reliably on
  916. // some Android 11+ devices
  917. // - Testing indicates that the NetworkRequest can sometimes
  918. // select the wrong network
  919. // - e.g., mobile instead of WiFi, and return the wrong DNS
  920. // servers
  921. // - there's currently no way to filter for the "currently
  922. // active default data network" returned by, e.g., the
  923. // deprecated getActiveNetworkInfo
  924. // - we cannot add the NET_CAPABILITY_FOREGROUND capability to
  925. // the NetworkRequest at this time due to target SDK
  926. // constraints
  927. NetworkRequest.Builder networkRequestBuilder = new NetworkRequest.Builder()
  928. .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
  929. if (isVpnMode) {
  930. // In VPN mode, we want the DNS servers for the underlying physical network.
  931. networkRequestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
  932. }
  933. NetworkRequest networkRequest = networkRequestBuilder.build();
  934. // There is a potential race condition in which the following
  935. // network callback may be invoked, by a worker thread, after
  936. // unregisterNetworkCallback. Synchronized access to a local
  937. // ArrayList copy avoids the
  938. // java.util.ConcurrentModificationException crash we previously
  939. // observed when getActiveNetworkDNSServers iterated over the
  940. // same ArrayList object value that was modified by the
  941. // callback.
  942. //
  943. // The late invocation of the callback still results in an empty
  944. // list of DNS servers, but this behavior has been observed only
  945. // in artificial conditions while rapidly starting and stopping
  946. // PsiphonTunnel.
  947. ArrayList<InetAddress> callbackDnsAddresses = new ArrayList<>();
  948. final CountDownLatch countDownLatch = new CountDownLatch(1);
  949. try {
  950. ConnectivityManager.NetworkCallback networkCallback =
  951. new ConnectivityManager.NetworkCallback() {
  952. @Override
  953. public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {
  954. synchronized (callbackDnsAddresses) {
  955. callbackDnsAddresses.addAll(linkProperties.getDnsServers());
  956. }
  957. countDownLatch.countDown();
  958. }
  959. };
  960. connectivityManager.registerNetworkCallback(networkRequest, networkCallback);
  961. countDownLatch.await(1, TimeUnit.SECONDS);
  962. connectivityManager.unregisterNetworkCallback(networkCallback);
  963. } catch (RuntimeException ignored) {
  964. // Failed to register network callback
  965. } catch (InterruptedException e) {
  966. Thread.currentThread().interrupt();
  967. }
  968. synchronized (callbackDnsAddresses) {
  969. dnsAddresses.addAll(callbackDnsAddresses);
  970. }
  971. }
  972. return dnsAddresses;
  973. }
  974. private static boolean hasIPv6Route(Context context) throws Exception {
  975. try {
  976. // This logic mirrors the logic in
  977. // psiphon/common/resolver.hasRoutableIPv6Interface. That
  978. // function currently doesn't work on Android due to Go's
  979. // net.InterfaceAddrs failing on Android SDK 30+ (see Go issue
  980. // 40569). hasIPv6Route provides the same functionality via a
  981. // callback into Java code.
  982. // Note: don't exclude interfaces with the isPointToPoint
  983. // property, which is true for certain mobile networks.
  984. for (NetworkInterface netInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
  985. if (netInterface.isUp() &&
  986. !netInterface.isLoopback()) {
  987. for (InetAddress address : Collections.list(netInterface.getInetAddresses())) {
  988. // Per https://developer.android.com/reference/java/net/Inet6Address#textual-representation-of-ip-addresses,
  989. // "Java will never return an IPv4-mapped address.
  990. // These classes can take an IPv4-mapped address as
  991. // input, both in byte array and text
  992. // representation. However, it will be converted
  993. // into an IPv4 address." As such, when the type of
  994. // the IP address is Inet6Address, this should be
  995. // an actual IPv6 address.
  996. if (address instanceof Inet6Address &&
  997. !address.isLinkLocalAddress() &&
  998. !address.isSiteLocalAddress() &&
  999. !address.isMulticastAddress ()) {
  1000. return true;
  1001. }
  1002. }
  1003. }
  1004. }
  1005. } catch (SocketException e) {
  1006. throw new Exception("hasIPv6Route failed", e);
  1007. }
  1008. return false;
  1009. }
  1010. //----------------------------------------------------------------------------------------------
  1011. // Exception
  1012. //----------------------------------------------------------------------------------------------
  1013. public static class Exception extends java.lang.Exception {
  1014. private static final long serialVersionUID = 1L;
  1015. public Exception(String message) {
  1016. super(message);
  1017. }
  1018. public Exception(String message, Throwable cause) {
  1019. super(message + ": " + cause.getMessage());
  1020. }
  1021. }
  1022. //----------------------------------------------------------------------------------------------
  1023. // Network connectivity monitor
  1024. //----------------------------------------------------------------------------------------------
  1025. private static class NetworkMonitor {
  1026. private final NetworkChangeListener listener;
  1027. private ConnectivityManager.NetworkCallback networkCallback;
  1028. public NetworkMonitor(
  1029. NetworkChangeListener listener) {
  1030. this.listener = listener;
  1031. }
  1032. private void start(Context context) throws InterruptedException {
  1033. final CountDownLatch setNetworkPropertiesCountDownLatch = new CountDownLatch(1);
  1034. // Need API 21(LOLLIPOP)+ for ConnectivityManager.NetworkCallback
  1035. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
  1036. return;
  1037. }
  1038. ConnectivityManager connectivityManager =
  1039. (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  1040. if (connectivityManager == null) {
  1041. return;
  1042. }
  1043. networkCallback = new ConnectivityManager.NetworkCallback() {
  1044. private boolean isInitialState = true;
  1045. private Network currentActiveNetwork;
  1046. private void consumeActiveNetwork(Network network) {
  1047. if (isInitialState) {
  1048. isInitialState = false;
  1049. setCurrentActiveNetworkAndProperties(network);
  1050. return;
  1051. }
  1052. if (!network.equals(currentActiveNetwork)) {
  1053. setCurrentActiveNetworkAndProperties(network);
  1054. if (listener != null) {
  1055. listener.onChanged();
  1056. }
  1057. }
  1058. }
  1059. private void consumeLostNetwork(Network network) {
  1060. if (network.equals(currentActiveNetwork)) {
  1061. setCurrentActiveNetworkAndProperties(null);
  1062. if (listener != null) {
  1063. listener.onChanged();
  1064. }
  1065. }
  1066. }
  1067. private void setCurrentActiveNetworkAndProperties(Network network) {
  1068. currentActiveNetwork = network;
  1069. if (network == null) {
  1070. INSTANCE.mActiveNetworkType.set("NONE");
  1071. INSTANCE.mActiveNetworkDNSServers.set("");
  1072. INSTANCE.mHostService.onDiagnosticMessage("NetworkMonitor: clear current active network");
  1073. } else {
  1074. String networkType = "UNKNOWN";
  1075. try {
  1076. // Limitation: a network may have both CELLULAR
  1077. // and WIFI transports, or different network
  1078. // transport types entirely. This logic currently
  1079. // mimics the type determination logic in
  1080. // getNetworkID.
  1081. NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
  1082. if (capabilities != null) {
  1083. if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
  1084. networkType = "VPN";
  1085. } else if (capabilities.hasTransport(
  1086. NetworkCapabilities.TRANSPORT_CELLULAR)) {
  1087. networkType = "MOBILE";
  1088. } else if (capabilities.hasTransport(
  1089. NetworkCapabilities.TRANSPORT_WIFI)) {
  1090. networkType = "WIFI";
  1091. }
  1092. }
  1093. } catch (java.lang.Exception e) {
  1094. }
  1095. INSTANCE.mActiveNetworkType.set(networkType);
  1096. ArrayList<String> servers = new ArrayList<>();
  1097. try {
  1098. LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
  1099. if (linkProperties != null) {
  1100. List<InetAddress> serverAddresses = linkProperties.getDnsServers();
  1101. for (InetAddress serverAddress : serverAddresses) {
  1102. String server = serverAddress.toString();
  1103. if (server.startsWith("/")) {
  1104. server = server.substring(1);
  1105. }
  1106. servers.add(server);
  1107. }
  1108. }
  1109. } catch (java.lang.Exception ignored) {
  1110. }
  1111. // Use the workaround, comma-delimited format required for gobind.
  1112. INSTANCE.mActiveNetworkDNSServers.set(TextUtils.join(",", servers));
  1113. String message = "NetworkMonitor: set current active network " + networkType;
  1114. if (!servers.isEmpty()) {
  1115. // The DNS server address is potential PII and not logged.
  1116. message += " with DNS";
  1117. }
  1118. INSTANCE.mHostService.onDiagnosticMessage(message);
  1119. }
  1120. setNetworkPropertiesCountDownLatch.countDown();
  1121. }
  1122. @Override
  1123. public void onCapabilitiesChanged(Network network, NetworkCapabilities capabilities) {
  1124. super.onCapabilitiesChanged(network, capabilities);
  1125. // Need API 23(M)+ for NET_CAPABILITY_VALIDATED
  1126. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
  1127. return;
  1128. }
  1129. // https://developer.android.com/reference/android/net/NetworkCapabilities#NET_CAPABILITY_VALIDATED
  1130. // Indicates that connectivity on this network was successfully validated.
  1131. // For example, for a network with NET_CAPABILITY_INTERNET, it means that Internet connectivity was
  1132. // successfully detected.
  1133. if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
  1134. consumeActiveNetwork(network);
  1135. }
  1136. }
  1137. @Override
  1138. public void onAvailable(Network network) {
  1139. super.onAvailable(network);
  1140. // Skip on API 26(O)+ because onAvailable is guaranteed to be followed by
  1141. // onCapabilitiesChanged
  1142. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  1143. return;
  1144. }
  1145. consumeActiveNetwork(network);
  1146. }
  1147. @Override
  1148. public void onLost(Network network) {
  1149. super.onLost(network);
  1150. consumeLostNetwork(network);
  1151. }
  1152. };
  1153. try {
  1154. // When searching for a network to satisfy a request, all capabilities requested must be satisfied.
  1155. NetworkRequest.Builder builder = new NetworkRequest.Builder()
  1156. // Indicates that this network should be able to reach the internet.
  1157. .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
  1158. if (INSTANCE.mVpnMode.get()) {
  1159. // If we are in the VPN mode then ensure we monitor only the VPN's underlying
  1160. // active networks and not self.
  1161. builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
  1162. } else {
  1163. // If we are NOT in the VPN mode then monitor default active networks with the
  1164. // Internet capability, including VPN, to ensure we won't trigger a reconnect in
  1165. // case the VPN is up while the system switches the underlying network.
  1166. // Limitation: for Psiphon Library apps running over Psiphon VPN, or other VPNs
  1167. // with a similar architecture, it may be better to trigger a reconnect when
  1168. // the underlying physical network changes. When the underlying network
  1169. // changes, Psiphon VPN will remain up and reconnect its own tunnel. For the
  1170. // Psiphon app, this monitoring will detect no change. However, the Psiphon
  1171. // app's tunnel may be lost, and, without network change detection, initiating
  1172. // a reconnect will be delayed. For example, if the Psiphon app's tunnel is
  1173. // using QUIC, the Psiphon VPN will tunnel that traffic over udpgw. When
  1174. // Psiphon VPN reconnects, the egress source address of that UDP flow will
  1175. // change -- getting either a different source IP if the Psiphon server
  1176. // changes, or a different source port even if the same server -- and the QUIC
  1177. // server will drop the packets. The Psiphon app will initiate a reconnect only
  1178. // after a SSH keep alive probes timeout or a QUIC timeout.
  1179. //
  1180. // TODO: Add a second ConnectivityManager/NetworkRequest instance to monitor
  1181. // for underlying physical network changes while any VPN remains up.
  1182. builder.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
  1183. }
  1184. NetworkRequest networkRequest = builder.build();
  1185. // We are using requestNetwork and not registerNetworkCallback here because we found
  1186. // that the callbacks from requestNetwork are more accurate in terms of tracking
  1187. // currently active network. Another alternative to use for tracking active network
  1188. // would be registerDefaultNetworkCallback but a) it needs API >= 24 and b) doesn't
  1189. // provide a way to set up monitoring of underlying networks only when VPN transport
  1190. // is also active.
  1191. connectivityManager.requestNetwork(networkRequest, networkCallback);
  1192. } catch (RuntimeException ignored) {
  1193. // Could be a security exception or any other runtime exception on customized firmwares.
  1194. networkCallback = null;
  1195. }
  1196. // We are going to wait up to one second for the network callback to populate
  1197. // active network properties before returning.
  1198. setNetworkPropertiesCountDownLatch.await(1, TimeUnit.SECONDS);
  1199. }
  1200. private void stop(Context context) {
  1201. if (networkCallback == null) {
  1202. return;
  1203. }
  1204. // Need API 21(LOLLIPOP)+ for ConnectivityManager.NetworkCallback
  1205. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
  1206. return;
  1207. }
  1208. ConnectivityManager connectivityManager =
  1209. (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  1210. if (connectivityManager == null) {
  1211. return;
  1212. }
  1213. // Note: ConnectivityManager.unregisterNetworkCallback() may throw
  1214. // "java.lang.IllegalArgumentException: NetworkCallback was not registered".
  1215. // This scenario should be handled in the start() above but we'll add a try/catch
  1216. // anyway to match the start's call to ConnectivityManager.registerNetworkCallback()
  1217. try {
  1218. connectivityManager.unregisterNetworkCallback(networkCallback);
  1219. } catch (RuntimeException ignored) {
  1220. }
  1221. networkCallback = null;
  1222. }
  1223. public interface NetworkChangeListener {
  1224. void onChanged();
  1225. }
  1226. }
  1227. }