PsiphonTunnel.java 70 KB

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