PsiphonTunnel.java 65 KB

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