PsiphonTunnel.java 71 KB

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