PsiphonTunnel.java 73 KB

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