PsiphonTunnel.java 66 KB

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