PsiphonTunnel.java 70 KB

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