PsiphonTunnel.java 67 KB

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