PsiphonTunnel.java 70 KB

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