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