PsiphonTunnel.java 67 KB

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