PsiphonTunnel.java 65 KB

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