PsiphonTunnel.java 64 KB

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