PsiphonTunnel.java 65 KB

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