PsiphonTunnel.java 73 KB

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