PsiphonTunnel.java 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  1. /*
  2. * Copyright (c) 2015, 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.annotation.TargetApi;
  21. import android.content.Context;
  22. import android.net.ConnectivityManager;
  23. import android.net.LinkProperties;
  24. import android.net.NetworkInfo;
  25. import android.net.VpnService;
  26. import android.net.wifi.WifiInfo;
  27. import android.net.wifi.WifiManager;
  28. import android.os.Build;
  29. import android.os.ParcelFileDescriptor;
  30. import android.telephony.TelephonyManager;
  31. import android.util.Base64;
  32. import org.json.JSONArray;
  33. import org.json.JSONException;
  34. import org.json.JSONObject;
  35. import java.io.File;
  36. import java.io.FileInputStream;
  37. import java.io.FileOutputStream;
  38. import java.io.IOException;
  39. import java.io.PrintStream;
  40. import java.lang.reflect.InvocationTargetException;
  41. import java.lang.reflect.Method;
  42. import java.net.Inet4Address;
  43. import java.net.InetAddress;
  44. import java.net.NetworkInterface;
  45. import java.net.SocketException;
  46. import java.security.KeyStore;
  47. import java.security.KeyStoreException;
  48. import java.security.NoSuchAlgorithmException;
  49. import java.security.cert.CertificateException;
  50. import java.security.cert.X509Certificate;
  51. import java.util.ArrayList;
  52. import java.util.Collection;
  53. import java.util.Collections;
  54. import java.util.Enumeration;
  55. import java.util.HashMap;
  56. import java.util.List;
  57. import java.util.Locale;
  58. import java.util.Map;
  59. import java.util.concurrent.atomic.AtomicBoolean;
  60. import java.util.concurrent.atomic.AtomicInteger;
  61. import java.util.concurrent.atomic.AtomicReference;
  62. import java.util.concurrent.Executors;
  63. import java.util.concurrent.ExecutorService;
  64. import psi.Psi;
  65. import psi.PsiphonProvider;
  66. import psi.PsiphonProviderNoticeHandler;
  67. import psi.PsiphonProviderFeedbackHandler;
  68. public class PsiphonTunnel {
  69. public interface HostLogger {
  70. default public void onDiagnosticMessage(String message) {}
  71. }
  72. // Protocol used to communicate the outcome of feedback upload operations to the application
  73. // using PsiphonTunnelFeedback.
  74. public interface HostFeedbackHandler {
  75. // Callback which is invoked once the feedback upload has completed.
  76. // If the exception is non-null, then the upload failed.
  77. default public void sendFeedbackCompleted(java.lang.Exception e) {}
  78. }
  79. public interface HostService extends HostLogger {
  80. public String getAppName();
  81. public Context getContext();
  82. public String getPsiphonConfig();
  83. default public Object getVpnService() {return null;} // Object must be a VpnService (Android < 4 cannot reference this class name)
  84. default public Object newVpnServiceBuilder() {return null;} // Object must be a VpnService.Builder (Android < 4 cannot reference this class name)
  85. default public void onAvailableEgressRegions(List<String> regions) {}
  86. default public void onSocksProxyPortInUse(int port) {}
  87. default public void onHttpProxyPortInUse(int port) {}
  88. default public void onListeningSocksProxyPort(int port) {}
  89. default public void onListeningHttpProxyPort(int port) {}
  90. default public void onUpstreamProxyError(String message) {}
  91. default public void onConnecting() {}
  92. default public void onConnected() {}
  93. default public void onHomepage(String url) {}
  94. default public void onClientRegion(String region) {}
  95. default public void onClientUpgradeDownloaded(String filename) {}
  96. default public void onClientIsLatestVersion() {}
  97. default public void onSplitTunnelRegion(String region) {}
  98. default public void onUntunneledAddress(String address) {}
  99. default public void onBytesTransferred(long sent, long received) {}
  100. default public void onStartedWaitingForNetworkConnectivity() {}
  101. default public void onStoppedWaitingForNetworkConnectivity() {}
  102. default public void onActiveAuthorizationIDs(List<String> authorizations) {}
  103. default public void onTrafficRateLimits(long upstreamBytesPerSecond, long downstreamBytesPerSecond) {}
  104. default public void onApplicationParameter(String key, Object value) {}
  105. default public void onServerAlert(String reason, String subject) {}
  106. default public void onExiting() {}
  107. }
  108. private final HostService mHostService;
  109. private AtomicBoolean mVpnMode;
  110. private PrivateAddress mPrivateAddress;
  111. private AtomicReference<ParcelFileDescriptor> mTunFd;
  112. private AtomicInteger mLocalSocksProxyPort;
  113. private AtomicBoolean mRoutingThroughTunnel;
  114. private Thread mTun2SocksThread;
  115. private AtomicBoolean mIsWaitingForNetworkConnectivity;
  116. private AtomicReference<String> mClientPlatformPrefix;
  117. private AtomicReference<String> mClientPlatformSuffix;
  118. private final boolean mShouldRouteThroughTunnelAutomatically;
  119. // Only one PsiphonVpn instance may exist at a time, as the underlying
  120. // psi.Psi and tun2socks implementations each contain global state.
  121. private static PsiphonTunnel mPsiphonTunnel;
  122. public static synchronized PsiphonTunnel newPsiphonTunnel(HostService hostService) {
  123. return newPsiphonTunnelImpl(hostService, true);
  124. }
  125. // The two argument override in case the host app wants to take control over calling routeThroughTunnel()
  126. public static synchronized PsiphonTunnel newPsiphonTunnel(HostService hostService, boolean shouldRouteThroughTunnelAutomatically) {
  127. return newPsiphonTunnelImpl(hostService, shouldRouteThroughTunnelAutomatically);
  128. }
  129. private static PsiphonTunnel newPsiphonTunnelImpl(HostService hostService, boolean shouldRouteThroughTunnelAutomatically) {
  130. if (mPsiphonTunnel != null) {
  131. mPsiphonTunnel.stop();
  132. }
  133. // Load the native go code embedded in psi.aar
  134. System.loadLibrary("gojni");
  135. mPsiphonTunnel = new PsiphonTunnel(hostService, shouldRouteThroughTunnelAutomatically);
  136. return mPsiphonTunnel;
  137. }
  138. // Returns default path where upgrade downloads will be paved. Only applicable if
  139. // DataRootDirectory was not set in the outer config. If DataRootDirectory was set in the
  140. // outer config, use getUpgradeDownloadFilePath with its value instead.
  141. public static String getDefaultUpgradeDownloadFilePath(Context context) {
  142. return Psi.upgradeDownloadFilePath(defaultDataRootDirectory(context).getAbsolutePath());
  143. }
  144. // Returns the path where upgrade downloads will be paved relative to the configured
  145. // DataRootDirectory.
  146. public static String getUpgradeDownloadFilePath(String dataRootDirectoryPath) {
  147. return Psi.upgradeDownloadFilePath(dataRootDirectoryPath);
  148. }
  149. private static File defaultDataRootDirectory(Context context) {
  150. return context.getFileStreamPath("ca.psiphon.PsiphonTunnel.tunnel-core");
  151. }
  152. private PsiphonTunnel(HostService hostService, boolean shouldRouteThroughTunnelAutomatically) {
  153. mHostService = hostService;
  154. mVpnMode = new AtomicBoolean(false);
  155. mTunFd = new AtomicReference<ParcelFileDescriptor>();
  156. mLocalSocksProxyPort = new AtomicInteger(0);
  157. mRoutingThroughTunnel = new AtomicBoolean(false);
  158. mIsWaitingForNetworkConnectivity = new AtomicBoolean(false);
  159. mClientPlatformPrefix = new AtomicReference<String>("");
  160. mClientPlatformSuffix = new AtomicReference<String>("");
  161. mShouldRouteThroughTunnelAutomatically = shouldRouteThroughTunnelAutomatically;
  162. }
  163. public Object clone() throws CloneNotSupportedException {
  164. throw new CloneNotSupportedException();
  165. }
  166. //----------------------------------------------------------------------------------------------
  167. // Public API
  168. //----------------------------------------------------------------------------------------------
  169. // To start, call in sequence: startRouting(), then startTunneling(). After startRouting()
  170. // succeeds, the caller must call stop() to clean up. These functions should not be called
  171. // concurrently. Do not call stop() while startRouting() or startTunneling() is in progress.
  172. // In case the host application requests manual control of routing through tunnel by calling
  173. // PsiphonTunnel.newPsiphonTunnel(HostService hostservice, shouldRouteThroughTunnelAutomatically = false)
  174. // it should also call routeThroughTunnel() at some point, usually after receiving onConnected() callback,
  175. // otherwise it will be called automatically.
  176. // Returns true when the VPN routing is established; returns false if the VPN could not
  177. // be started due to lack of prepare or revoked permissions (called should re-prepare and
  178. // try again); throws exception for other error conditions.
  179. public synchronized boolean startRouting() throws Exception {
  180. // Load tun2socks library embedded in the aar
  181. // If this method is called more than once with the same library name, the second and subsequent calls are ignored.
  182. // http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#loadLibrary%28java.lang.String%29
  183. System.loadLibrary("tun2socks");
  184. return startVpn();
  185. }
  186. // Starts routing traffic via tunnel by starting tun2socks if it is not running already.
  187. // This will be called automatically right after tunnel gets connected in case the host application
  188. // did not request a manual control over this functionality, see PsiphonTunnel.newPsiphonTunnel
  189. public void routeThroughTunnel() {
  190. if (!mRoutingThroughTunnel.compareAndSet(false, true)) {
  191. return;
  192. }
  193. ParcelFileDescriptor tunFd = mTunFd.getAndSet(null);
  194. if (tunFd == null) {
  195. return;
  196. }
  197. String socksServerAddress = "127.0.0.1:" + Integer.toString(mLocalSocksProxyPort.get());
  198. String udpgwServerAddress = "127.0.0.1:" + Integer.toString(UDPGW_SERVER_PORT);
  199. startTun2Socks(
  200. tunFd,
  201. VPN_INTERFACE_MTU,
  202. mPrivateAddress.mRouter,
  203. VPN_INTERFACE_NETMASK,
  204. socksServerAddress,
  205. udpgwServerAddress,
  206. true);
  207. mHostService.onDiagnosticMessage("routing through tunnel");
  208. // TODO: should double-check tunnel routing; see:
  209. // https://bitbucket.org/psiphon/psiphon-circumvention-system/src/1dc5e4257dca99790109f3bf374e8ab3a0ead4d7/Android/PsiphonAndroidLibrary/src/com/psiphon3/psiphonlibrary/TunnelCore.java?at=default#cl-779
  210. }
  211. // Throws an exception in error conditions. In the case of an exception, the routing
  212. // started by startRouting() is not immediately torn down (this allows the caller to control
  213. // exactly when VPN routing is stopped); caller should call stop() to clean up.
  214. public synchronized void startTunneling(String embeddedServerEntries) throws Exception {
  215. startPsiphon(embeddedServerEntries);
  216. }
  217. // Note: to avoid deadlock, do not call directly from a HostService callback;
  218. // instead post to a Handler if necessary to trigger from a HostService callback.
  219. // For example, deadlock can occur when a Notice callback invokes stop() since stop() calls
  220. // Psi.stop() which will block waiting for tunnel-core Controller to shutdown which in turn
  221. // waits for Notice callback invoker to stop, meanwhile the callback thread has blocked waiting
  222. // for stop().
  223. public synchronized void stop() {
  224. stopVpn();
  225. stopPsiphon();
  226. mVpnMode.set(false);
  227. mLocalSocksProxyPort.set(0);
  228. }
  229. // Note: same deadlock note as stop().
  230. public synchronized void restartPsiphon() throws Exception {
  231. stopPsiphon();
  232. startPsiphon("");
  233. }
  234. // Creates a temporary dummy VPN interface in order to prevent traffic leaking while performing
  235. // complete VPN and tunnel restart, for example, caused by host app settings change.
  236. // Note: same deadlock note as stop().
  237. @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
  238. public synchronized void seamlessVpnRestart(VpnService.Builder vpnServiceBuilder) throws Exception {
  239. // Perform seamless VPN interface swap Psiphon VPN -> dummy VPN
  240. //
  241. // From https://developer.android.com/reference/android/net/VpnService.Builder.html#establish()
  242. // "However, it is rare but not impossible to have two interfaces while performing a seamless handover.
  243. // In this case, the old interface will be deactivated when the new one is created successfully. Both
  244. // file descriptors are valid but now outgoing packets will be routed to the new interface. Therefore,
  245. // after draining the old file descriptor, the application MUST close it and start using the new file
  246. // descriptor."
  247. ParcelFileDescriptor dummyVpnFd = startDummyVpn(vpnServiceBuilder);
  248. try {
  249. // Clean up and restart Psiphon VPN interface, which will also do the swap dummy VPN -> Psiphon VPN
  250. stopVpn();
  251. startVpn();
  252. } finally {
  253. // Close dummy VPN file descriptor as per documentation.
  254. if (dummyVpnFd != null) {
  255. try {
  256. dummyVpnFd.close();
  257. } catch (IOException e) {
  258. }
  259. }
  260. }
  261. // Restart the tunnel.
  262. restartPsiphon();
  263. }
  264. public void setClientPlatformAffixes(String prefix, String suffix) {
  265. mClientPlatformPrefix.set(prefix);
  266. mClientPlatformSuffix.set(suffix);
  267. }
  268. public String exportExchangePayload() {
  269. return Psi.exportExchangePayload();
  270. }
  271. public boolean importExchangePayload(String payload) {
  272. return Psi.importExchangePayload(payload);
  273. }
  274. // Writes Go runtime profile information to a set of files in the specifiec output directory.
  275. // cpuSampleDurationSeconds and blockSampleDurationSeconds determines how to long to wait and
  276. // sample profiles that require active sampling. When set to 0, these profiles are skipped.
  277. public void writeRuntimeProfiles(String outputDirectory, int cpuSampleDurationSeconnds, int blockSampleDurationSeconds) {
  278. Psi.writeRuntimeProfiles(outputDirectory, cpuSampleDurationSeconnds, blockSampleDurationSeconds);
  279. }
  280. // The interface for managing the Psiphon feedback upload operations.
  281. // Warning: should not be used in the same process as PsiphonTunnel.
  282. public static class PsiphonTunnelFeedback {
  283. final private ExecutorService workQueue;
  284. final private ExecutorService callbackQueue;
  285. public PsiphonTunnelFeedback() {
  286. workQueue = Executors.newSingleThreadExecutor();
  287. callbackQueue = Executors.newSingleThreadExecutor();
  288. }
  289. // Upload a feedback package to Psiphon Inc. The app collects feedback and diagnostics
  290. // information in a particular format, then calls this function to upload it for later
  291. // investigation. The feedback compatible config and upload path must be provided by
  292. // Psiphon Inc. This call is asynchronous and returns before the upload completes. The
  293. // operation has completed when sendFeedbackCompleted() is called on the provided
  294. // HostFeedbackHandler. The provided HostLogger will be called to log informational notices,
  295. // including warnings.
  296. //
  297. // Warning: only one active upload is supported at a time. An ongoing upload will be
  298. // cancelled if this function is called again before it completes.
  299. public void startSendFeedback(Context context, HostFeedbackHandler feedbackHandler, HostLogger logger,
  300. String feedbackConfigJson, String diagnosticsJson, String uploadPath,
  301. String clientPlatformPrefix, String clientPlatformSuffix) {
  302. workQueue.submit(new Runnable() {
  303. @Override
  304. public void run() {
  305. try {
  306. // Adds fields used in feedback upload, e.g. client platform.
  307. String psiphonConfig = buildPsiphonConfig(context, logger, feedbackConfigJson,
  308. clientPlatformPrefix, clientPlatformSuffix, false, 0);
  309. Psi.startSendFeedback(psiphonConfig, diagnosticsJson, uploadPath,
  310. new PsiphonProviderFeedbackHandler() {
  311. @Override
  312. public void sendFeedbackCompleted(java.lang.Exception e) {
  313. callbackQueue.submit(new Runnable() {
  314. @Override
  315. public void run() {
  316. feedbackHandler.sendFeedbackCompleted(e);
  317. }
  318. });
  319. }
  320. },
  321. new PsiphonProviderNoticeHandler() {
  322. @Override
  323. public void notice(String noticeJSON) {
  324. try {
  325. JSONObject notice = new JSONObject(noticeJSON);
  326. String noticeType = notice.getString("noticeType");
  327. if (noticeType == null) {
  328. return;
  329. }
  330. JSONObject data = notice.getJSONObject("data");
  331. if (data == null) {
  332. return;
  333. }
  334. String diagnosticMessage = noticeType + ": " + data.toString();
  335. callbackQueue.submit(new Runnable() {
  336. @Override
  337. public void run() {
  338. logger.onDiagnosticMessage(diagnosticMessage);
  339. }
  340. });
  341. } catch (java.lang.Exception e) {
  342. callbackQueue.submit(new Runnable() {
  343. @Override
  344. public void run() {
  345. logger.onDiagnosticMessage("Error handling notice " + e.toString());
  346. }
  347. });
  348. }
  349. }
  350. });
  351. } catch (java.lang.Exception e) {
  352. feedbackHandler.sendFeedbackCompleted(new Exception("Error sending feedback", e));
  353. }
  354. }
  355. });
  356. }
  357. // Interrupt an in-progress feedback upload operation started with startSendFeedback.
  358. public void stopSendFeedback() {
  359. workQueue.submit(new Runnable() {
  360. @Override
  361. public void run() {
  362. Psi.stopSendFeedback();
  363. }
  364. });
  365. }
  366. }
  367. //----------------------------------------------------------------------------------------------
  368. // VPN Routing
  369. //----------------------------------------------------------------------------------------------
  370. private final static String VPN_INTERFACE_NETMASK = "255.255.255.0";
  371. private final static int VPN_INTERFACE_MTU = 1500;
  372. private final static int UDPGW_SERVER_PORT = 7300;
  373. private final static String DEFAULT_PRIMARY_DNS_SERVER = "8.8.4.4";
  374. private final static String DEFAULT_SECONDARY_DNS_SERVER = "8.8.8.8";
  375. // Note: Atomic variables used for getting/setting local proxy port, routing flag, and
  376. // tun fd, as these functions may be called via PsiphonProvider callbacks. Do not use
  377. // synchronized functions as stop() is synchronized and a deadlock is possible as callbacks
  378. // can be called while stop holds the lock.
  379. @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
  380. private boolean startVpn() throws Exception {
  381. mVpnMode.set(true);
  382. mPrivateAddress = selectPrivateAddress();
  383. Locale previousLocale = Locale.getDefault();
  384. final String errorMessage = "startVpn failed";
  385. try {
  386. // Workaround for https://code.google.com/p/android/issues/detail?id=61096
  387. Locale.setDefault(new Locale("en"));
  388. int mtu = VPN_INTERFACE_MTU;
  389. String dnsResolver = mPrivateAddress.mRouter;
  390. ParcelFileDescriptor tunFd =
  391. ((VpnService.Builder) mHostService.newVpnServiceBuilder())
  392. .setSession(mHostService.getAppName())
  393. .setMtu(mtu)
  394. .addAddress(mPrivateAddress.mIpAddress, mPrivateAddress.mPrefixLength)
  395. .addRoute("0.0.0.0", 0)
  396. .addRoute(mPrivateAddress.mSubnet, mPrivateAddress.mPrefixLength)
  397. .addDnsServer(dnsResolver)
  398. .establish();
  399. if (tunFd == null) {
  400. // As per http://developer.android.com/reference/android/net/VpnService.Builder.html#establish%28%29,
  401. // this application is no longer prepared or was revoked.
  402. return false;
  403. }
  404. mTunFd.set(tunFd);
  405. mRoutingThroughTunnel.set(false);
  406. mHostService.onDiagnosticMessage("VPN established");
  407. } catch(IllegalArgumentException e) {
  408. throw new Exception(errorMessage, e);
  409. } catch(IllegalStateException e) {
  410. throw new Exception(errorMessage, e);
  411. } catch(SecurityException e) {
  412. throw new Exception(errorMessage, e);
  413. } finally {
  414. // Restore the original locale.
  415. Locale.setDefault(previousLocale);
  416. }
  417. return true;
  418. }
  419. @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
  420. private ParcelFileDescriptor startDummyVpn(VpnService.Builder vpnServiceBuilder) throws Exception {
  421. PrivateAddress privateAddress = selectPrivateAddress();
  422. Locale previousLocale = Locale.getDefault();
  423. final String errorMessage = "startDummyVpn failed";
  424. final ParcelFileDescriptor tunFd;
  425. try {
  426. // Workaround for https://code.google.com/p/android/issues/detail?id=61096
  427. Locale.setDefault(new Locale("en"));
  428. int mtu = VPN_INTERFACE_MTU;
  429. String dnsResolver = privateAddress.mRouter;
  430. tunFd = vpnServiceBuilder
  431. .setSession(mHostService.getAppName())
  432. .setMtu(mtu)
  433. .addAddress(privateAddress.mIpAddress, privateAddress.mPrefixLength)
  434. .addRoute("0.0.0.0", 0)
  435. .addRoute(privateAddress.mSubnet, privateAddress.mPrefixLength)
  436. .addDnsServer(dnsResolver)
  437. .establish();
  438. } catch(IllegalArgumentException e) {
  439. throw new Exception(errorMessage, e);
  440. } catch(IllegalStateException e) {
  441. throw new Exception(errorMessage, e);
  442. } catch(SecurityException e) {
  443. throw new Exception(errorMessage, e);
  444. } finally {
  445. // Restore the original locale.
  446. Locale.setDefault(previousLocale);
  447. }
  448. return tunFd;
  449. }
  450. private boolean isVpnMode() {
  451. return mVpnMode.get();
  452. }
  453. private void setLocalSocksProxyPort(int port) {
  454. mLocalSocksProxyPort.set(port);
  455. }
  456. private void stopVpn() {
  457. stopTun2Socks();
  458. ParcelFileDescriptor tunFd = mTunFd.getAndSet(null);
  459. if (tunFd != null) {
  460. try {
  461. tunFd.close();
  462. } catch (IOException e) {
  463. }
  464. }
  465. mRoutingThroughTunnel.set(false);
  466. }
  467. //----------------------------------------------------------------------------------------------
  468. // PsiphonProvider (Core support) interface implementation
  469. //----------------------------------------------------------------------------------------------
  470. // The PsiphonProvider functions are called from Go, and must be public to be accessible
  471. // via the gobind mechanim. To avoid making internal implementation functions public,
  472. // PsiphonProviderShim is used as a wrapper.
  473. private class PsiphonProviderShim implements PsiphonProvider {
  474. private PsiphonTunnel mPsiphonTunnel;
  475. public PsiphonProviderShim(PsiphonTunnel psiphonTunnel) {
  476. mPsiphonTunnel = psiphonTunnel;
  477. }
  478. @Override
  479. public void notice(String noticeJSON) {
  480. mPsiphonTunnel.notice(noticeJSON);
  481. }
  482. @Override
  483. public String bindToDevice(long fileDescriptor) throws Exception {
  484. return mPsiphonTunnel.bindToDevice(fileDescriptor);
  485. }
  486. @Override
  487. public long hasNetworkConnectivity() {
  488. return mPsiphonTunnel.hasNetworkConnectivity();
  489. }
  490. @Override
  491. public String getPrimaryDnsServer() {
  492. return mPsiphonTunnel.getPrimaryDnsServer();
  493. }
  494. @Override
  495. public String getSecondaryDnsServer() {
  496. return mPsiphonTunnel.getSecondaryDnsServer();
  497. }
  498. @Override
  499. public String iPv6Synthesize(String IPv4Addr) {
  500. return mPsiphonTunnel.iPv6Synthesize(IPv4Addr);
  501. }
  502. @Override
  503. public String getNetworkID() {
  504. return mPsiphonTunnel.getNetworkID();
  505. }
  506. }
  507. private void notice(String noticeJSON) {
  508. handlePsiphonNotice(noticeJSON);
  509. }
  510. @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
  511. private String bindToDevice(long fileDescriptor) throws Exception {
  512. if (!((VpnService)mHostService.getVpnService()).protect((int)fileDescriptor)) {
  513. throw new Exception("protect socket failed");
  514. }
  515. return "";
  516. }
  517. private long hasNetworkConnectivity() {
  518. boolean hasConnectivity = hasNetworkConnectivity(mHostService.getContext());
  519. boolean wasWaitingForNetworkConnectivity = mIsWaitingForNetworkConnectivity.getAndSet(!hasConnectivity);
  520. // HasNetworkConnectivity may be called many times, but only invoke
  521. // callbacks once per loss or resumption of connectivity, so, e.g.,
  522. // the HostService may log a single message.
  523. if (!hasConnectivity && !wasWaitingForNetworkConnectivity) {
  524. mHostService.onStartedWaitingForNetworkConnectivity();
  525. } else if (hasConnectivity && wasWaitingForNetworkConnectivity) {
  526. mHostService.onStoppedWaitingForNetworkConnectivity();
  527. }
  528. // TODO: change to bool return value once gobind supports that type
  529. return hasConnectivity ? 1 : 0;
  530. }
  531. private String getPrimaryDnsServer() {
  532. String dnsResolver = null;
  533. try {
  534. dnsResolver = getFirstActiveNetworkDnsResolver(mHostService.getContext());
  535. } catch (Exception e) {
  536. mHostService.onDiagnosticMessage("failed to get active network DNS resolver: " + e.getMessage());
  537. dnsResolver = DEFAULT_PRIMARY_DNS_SERVER;
  538. }
  539. return dnsResolver;
  540. }
  541. private String getSecondaryDnsServer() {
  542. return DEFAULT_SECONDARY_DNS_SERVER;
  543. }
  544. private String iPv6Synthesize(String IPv4Addr) {
  545. return IPv4Addr;
  546. }
  547. private String getNetworkID() {
  548. // The network ID contains potential PII. In tunnel-core, the network ID
  549. // is used only locally in the client and not sent to the server.
  550. //
  551. // See network ID requirements here:
  552. // https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter
  553. String networkID = "UNKNOWN";
  554. Context context = mHostService.getContext();
  555. ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  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. WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
  568. WifiInfo wifiInfo = wifiManager.getConnectionInfo();
  569. if (wifiInfo != null) {
  570. String wifiNetworkID = wifiInfo.getBSSID();
  571. if (wifiNetworkID.equals("02:00:00:00:00:00")) {
  572. // "02:00:00:00:00:00" is reported when the app does not have the ACCESS_COARSE_LOCATION permission:
  573. // https://developer.android.com/about/versions/marshmallow/android-6.0-changes#behavior-hardware-id
  574. // The Psiphon client should allow the user to opt-in to this permission. If they decline, fail over
  575. // to using the WiFi IP address.
  576. wifiNetworkID = String.valueOf(wifiInfo.getIpAddress());
  577. }
  578. networkID += "-" + wifiNetworkID;
  579. }
  580. } catch (java.lang.Exception e) {
  581. // May get exceptions due to missing permissions like android.permission.ACCESS_WIFI_STATE.
  582. // Fall through and use just "WIFI"
  583. }
  584. } else if (activeNetworkInfo != null && activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
  585. networkID = "MOBILE";
  586. try {
  587. TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
  588. if (telephonyManager != null) {
  589. networkID += "-" + telephonyManager.getNetworkOperator();
  590. }
  591. } catch (java.lang.Exception e) {
  592. // May get exceptions due to missing permissions.
  593. // Fall through and use just "MOBILE"
  594. }
  595. }
  596. return networkID;
  597. }
  598. //----------------------------------------------------------------------------------------------
  599. // Psiphon Tunnel Core
  600. //----------------------------------------------------------------------------------------------
  601. private void startPsiphon(String embeddedServerEntries) throws Exception {
  602. stopPsiphon();
  603. mIsWaitingForNetworkConnectivity.set(false);
  604. mHostService.onDiagnosticMessage("starting Psiphon library");
  605. try {
  606. Psi.start(
  607. loadPsiphonConfig(mHostService.getContext()),
  608. embeddedServerEntries,
  609. "",
  610. new PsiphonProviderShim(this),
  611. isVpnMode(),
  612. false // Do not use IPv6 synthesizer for android
  613. );
  614. } catch (java.lang.Exception e) {
  615. throw new Exception("failed to start Psiphon library", e);
  616. }
  617. mHostService.onDiagnosticMessage("Psiphon library started");
  618. }
  619. private void stopPsiphon() {
  620. mHostService.onDiagnosticMessage("stopping Psiphon library");
  621. Psi.stop();
  622. mHostService.onDiagnosticMessage("Psiphon library stopped");
  623. }
  624. private String loadPsiphonConfig(Context context)
  625. throws IOException, JSONException, Exception {
  626. return buildPsiphonConfig(context, mHostService, mHostService.getPsiphonConfig(),
  627. mClientPlatformPrefix.get(), mClientPlatformSuffix.get(), isVpnMode(),
  628. mLocalSocksProxyPort.get());
  629. }
  630. private static String buildPsiphonConfig(Context context, HostLogger logger, String psiphonConfig,
  631. String clientPlatformPrefix, String clientPlatformSuffix,
  632. boolean isVpnMode, Integer localSocksProxyPort)
  633. throws IOException, JSONException, Exception {
  634. // Load settings from the raw resource JSON config file and
  635. // update as necessary. Then write JSON to disk for the Go client.
  636. JSONObject json = new JSONObject(psiphonConfig);
  637. // On Android, this directory must be set to the app private storage area.
  638. // The Psiphon library won't be able to use its current working directory
  639. // and the standard temporary directories do not exist.
  640. if (!json.has("DataRootDirectory")) {
  641. File dataRootDirectory = defaultDataRootDirectory(context);
  642. if (!dataRootDirectory.exists()) {
  643. boolean created = dataRootDirectory.mkdir();
  644. if (!created) {
  645. throw new Exception("failed to create data root directory: " + dataRootDirectory.getPath());
  646. }
  647. }
  648. json.put("DataRootDirectory", defaultDataRootDirectory(context));
  649. }
  650. // Migrate datastore files from legacy directory.
  651. if (!json.has("DataStoreDirectory")) {
  652. json.put("MigrateDataStoreDirectory", context.getFilesDir());
  653. }
  654. // Migrate remote server list downloads from legacy location.
  655. if (!json.has("RemoteServerListDownloadFilename")) {
  656. File remoteServerListDownload = new File(context.getFilesDir(), "remote_server_list");
  657. json.put("MigrateRemoteServerListDownloadFilename", remoteServerListDownload.getAbsolutePath());
  658. }
  659. // Migrate obfuscated server list download files from legacy directory.
  660. File oslDownloadDir = new File(context.getFilesDir(), "osl");
  661. json.put("MigrateObfuscatedServerListDownloadDirectory", oslDownloadDir.getAbsolutePath());
  662. // Note: onConnecting/onConnected logic assumes 1 tunnel connection
  663. json.put("TunnelPoolSize", 1);
  664. // Continue to run indefinitely until connected
  665. if (!json.has("EstablishTunnelTimeoutSeconds")) {
  666. json.put("EstablishTunnelTimeoutSeconds", 0);
  667. }
  668. // This parameter is for stats reporting
  669. if (!json.has("TunnelWholeDevice")) {
  670. json.put("TunnelWholeDevice", isVpnMode ? 1 : 0);
  671. }
  672. json.put("EmitBytesTransferred", true);
  673. if (localSocksProxyPort != 0 && (!json.has("LocalSocksProxyPort") || json.getInt("LocalSocksProxyPort") == 0)) {
  674. // When mLocalSocksProxyPort is set, tun2socks is already configured
  675. // to use that port value. So we force use of the same port.
  676. // A side-effect of this is that changing the SOCKS port preference
  677. // has no effect with restartPsiphon(), a full stop() is necessary.
  678. json.put("LocalSocksProxyPort", localSocksProxyPort);
  679. }
  680. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
  681. try {
  682. json.put(
  683. "TrustedCACertificatesFilename",
  684. setupTrustedCertificates(context, logger));
  685. } catch (Exception e) {
  686. logger.onDiagnosticMessage(e.getMessage());
  687. }
  688. }
  689. json.put("DeviceRegion", getDeviceRegion(context));
  690. StringBuilder clientPlatform = new StringBuilder();
  691. if (clientPlatformPrefix.length() > 0) {
  692. clientPlatform.append(clientPlatformPrefix);
  693. }
  694. clientPlatform.append("Android_");
  695. clientPlatform.append(Build.VERSION.RELEASE);
  696. clientPlatform.append("_");
  697. clientPlatform.append(context.getPackageName());
  698. if (clientPlatformSuffix.length() > 0) {
  699. clientPlatform.append(clientPlatformSuffix);
  700. }
  701. json.put("ClientPlatform", clientPlatform.toString().replaceAll("[^\\w\\-\\.]", "_"));
  702. return json.toString();
  703. }
  704. private void handlePsiphonNotice(String noticeJSON) {
  705. try {
  706. // All notices are sent on as diagnostic messages
  707. // except those that may contain private user data.
  708. boolean diagnostic = true;
  709. JSONObject notice = new JSONObject(noticeJSON);
  710. String noticeType = notice.getString("noticeType");
  711. if (noticeType.equals("Tunnels")) {
  712. int count = notice.getJSONObject("data").getInt("count");
  713. if (count > 0) {
  714. if (isVpnMode() && mShouldRouteThroughTunnelAutomatically) {
  715. routeThroughTunnel();
  716. }
  717. mHostService.onConnected();
  718. } else {
  719. mHostService.onConnecting();
  720. }
  721. } else if (noticeType.equals("AvailableEgressRegions")) {
  722. JSONArray egressRegions = notice.getJSONObject("data").getJSONArray("regions");
  723. ArrayList<String> regions = new ArrayList<String>();
  724. for (int i=0; i<egressRegions.length(); i++) {
  725. regions.add(egressRegions.getString(i));
  726. }
  727. mHostService.onAvailableEgressRegions(regions);
  728. } else if (noticeType.equals("SocksProxyPortInUse")) {
  729. mHostService.onSocksProxyPortInUse(notice.getJSONObject("data").getInt("port"));
  730. } else if (noticeType.equals("HttpProxyPortInUse")) {
  731. mHostService.onHttpProxyPortInUse(notice.getJSONObject("data").getInt("port"));
  732. } else if (noticeType.equals("ListeningSocksProxyPort")) {
  733. int port = notice.getJSONObject("data").getInt("port");
  734. setLocalSocksProxyPort(port);
  735. mHostService.onListeningSocksProxyPort(port);
  736. } else if (noticeType.equals("ListeningHttpProxyPort")) {
  737. int port = notice.getJSONObject("data").getInt("port");
  738. mHostService.onListeningHttpProxyPort(port);
  739. } else if (noticeType.equals("UpstreamProxyError")) {
  740. mHostService.onUpstreamProxyError(notice.getJSONObject("data").getString("message"));
  741. } else if (noticeType.equals("ClientUpgradeDownloaded")) {
  742. mHostService.onClientUpgradeDownloaded(notice.getJSONObject("data").getString("filename"));
  743. } else if (noticeType.equals("ClientIsLatestVersion")) {
  744. mHostService.onClientIsLatestVersion();
  745. } else if (noticeType.equals("Homepage")) {
  746. mHostService.onHomepage(notice.getJSONObject("data").getString("url"));
  747. } else if (noticeType.equals("ClientRegion")) {
  748. mHostService.onClientRegion(notice.getJSONObject("data").getString("region"));
  749. } else if (noticeType.equals("SplitTunnelRegion")) {
  750. mHostService.onSplitTunnelRegion(notice.getJSONObject("data").getString("region"));
  751. } else if (noticeType.equals("Untunneled")) {
  752. mHostService.onUntunneledAddress(notice.getJSONObject("data").getString("address"));
  753. } else if (noticeType.equals("BytesTransferred")) {
  754. diagnostic = false;
  755. JSONObject data = notice.getJSONObject("data");
  756. mHostService.onBytesTransferred(data.getLong("sent"), data.getLong("received"));
  757. } else if (noticeType.equals("ActiveAuthorizationIDs")) {
  758. JSONArray activeAuthorizationIDs = notice.getJSONObject("data").getJSONArray("IDs");
  759. ArrayList<String> authorizations = new ArrayList<String>();
  760. for (int i=0; i<activeAuthorizationIDs.length(); i++) {
  761. authorizations.add(activeAuthorizationIDs.getString(i));
  762. }
  763. mHostService.onActiveAuthorizationIDs(authorizations);
  764. } else if (noticeType.equals("TrafficRateLimits")) {
  765. JSONObject data = notice.getJSONObject("data");
  766. mHostService.onTrafficRateLimits(
  767. data.getLong("upstreamBytesPerSecond"), data.getLong("downstreamBytesPerSecond"));
  768. } else if (noticeType.equals("Exiting")) {
  769. mHostService.onExiting();
  770. } else if (noticeType.equals("ActiveTunnel")) {
  771. if (isVpnMode()) {
  772. if (notice.getJSONObject("data").getBoolean("isTCS")) {
  773. disableUdpGwKeepalive();
  774. } else {
  775. enableUdpGwKeepalive();
  776. }
  777. }
  778. } else if (noticeType.equals("ApplicationParameter")) {
  779. mHostService.onApplicationParameter(
  780. notice.getJSONObject("data").getString("key"),
  781. notice.getJSONObject("data").get("value"));
  782. } else if (noticeType.equals("ServerAlert")) {
  783. mHostService.onServerAlert(
  784. notice.getJSONObject("data").getString("reason"),
  785. notice.getJSONObject("data").getString("subject"));
  786. }
  787. if (diagnostic) {
  788. String diagnosticMessage = noticeType + ": " + notice.getJSONObject("data").toString();
  789. mHostService.onDiagnosticMessage(diagnosticMessage);
  790. }
  791. } catch (JSONException e) {
  792. // Ignore notice
  793. }
  794. }
  795. private static String setupTrustedCertificates(Context context, HostLogger logger) throws Exception {
  796. // Copy the Android system CA store to a local, private cert bundle file.
  797. //
  798. // This results in a file that can be passed to SSL_CTX_load_verify_locations
  799. // for use with OpenSSL modes in tunnel-core.
  800. // https://www.openssl.org/docs/manmaster/ssl/SSL_CTX_load_verify_locations.html
  801. //
  802. // TODO: to use the path mode of load_verify_locations would require emulating
  803. // the filename scheme used by c_rehash:
  804. // https://www.openssl.org/docs/manmaster/apps/c_rehash.html
  805. // http://stackoverflow.com/questions/19237167/the-new-subject-hash-openssl-algorithm-differs
  806. File directory = context.getDir("PsiphonCAStore", Context.MODE_PRIVATE);
  807. final String errorMessage = "copy AndroidCAStore failed";
  808. try {
  809. File file = new File(directory, "certs.dat");
  810. // Pave a fresh copy on every run, which ensures we're not using old certs.
  811. // Note: assumes KeyStore doesn't return revoked certs.
  812. //
  813. // TODO: this takes under 1 second, but should we avoid repaving every time?
  814. file.delete();
  815. PrintStream output = null;
  816. try {
  817. output = new PrintStream(new FileOutputStream(file));
  818. KeyStore keyStore;
  819. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
  820. keyStore = KeyStore.getInstance("AndroidCAStore");
  821. keyStore.load(null, null);
  822. } else {
  823. keyStore = KeyStore.getInstance("BKS");
  824. FileInputStream inputStream = new FileInputStream("/etc/security/cacerts.bks");
  825. try {
  826. keyStore.load(inputStream, "changeit".toCharArray());
  827. } finally {
  828. if (inputStream != null) {
  829. inputStream.close();
  830. }
  831. }
  832. }
  833. Enumeration<String> aliases = keyStore.aliases();
  834. while (aliases.hasMoreElements()) {
  835. String alias = aliases.nextElement();
  836. X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
  837. output.println("-----BEGIN CERTIFICATE-----");
  838. String pemCert = new String(Base64.encode(cert.getEncoded(), Base64.NO_WRAP), "UTF-8");
  839. // OpenSSL appears to reject the default linebreaking done by Base64.encode,
  840. // so we manually linebreak every 64 characters
  841. for (int i = 0; i < pemCert.length() ; i+= 64) {
  842. output.println(pemCert.substring(i, Math.min(i + 64, pemCert.length())));
  843. }
  844. output.println("-----END CERTIFICATE-----");
  845. }
  846. logger.onDiagnosticMessage("prepared PsiphonCAStore");
  847. return file.getAbsolutePath();
  848. } finally {
  849. if (output != null) {
  850. output.close();
  851. }
  852. }
  853. } catch (KeyStoreException e) {
  854. throw new Exception(errorMessage, e);
  855. } catch (NoSuchAlgorithmException e) {
  856. throw new Exception(errorMessage, e);
  857. } catch (CertificateException e) {
  858. throw new Exception(errorMessage, e);
  859. } catch (IOException e) {
  860. throw new Exception(errorMessage, e);
  861. }
  862. }
  863. private static String getDeviceRegion(Context context) {
  864. String region = "";
  865. TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
  866. if (telephonyManager != null) {
  867. region = telephonyManager.getSimCountryIso();
  868. if (region == null) {
  869. region = "";
  870. }
  871. if (region.length() == 0 && telephonyManager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
  872. region = telephonyManager.getNetworkCountryIso();
  873. if (region == null) {
  874. region = "";
  875. }
  876. }
  877. }
  878. if (region.length() == 0) {
  879. Locale defaultLocale = Locale.getDefault();
  880. if (defaultLocale != null) {
  881. region = defaultLocale.getCountry();
  882. }
  883. }
  884. return region.toUpperCase(Locale.US);
  885. }
  886. //----------------------------------------------------------------------------------------------
  887. // Tun2Socks
  888. //----------------------------------------------------------------------------------------------
  889. @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
  890. private void startTun2Socks(
  891. final ParcelFileDescriptor vpnInterfaceFileDescriptor,
  892. final int vpnInterfaceMTU,
  893. final String vpnIpAddress,
  894. final String vpnNetMask,
  895. final String socksServerAddress,
  896. final String udpgwServerAddress,
  897. final boolean udpgwTransparentDNS) {
  898. if (mTun2SocksThread != null) {
  899. return;
  900. }
  901. mTun2SocksThread = new Thread(new Runnable() {
  902. @Override
  903. public void run() {
  904. runTun2Socks(
  905. vpnInterfaceFileDescriptor.detachFd(),
  906. vpnInterfaceMTU,
  907. vpnIpAddress,
  908. vpnNetMask,
  909. socksServerAddress,
  910. udpgwServerAddress,
  911. udpgwTransparentDNS ? 1 : 0);
  912. }
  913. });
  914. mTun2SocksThread.start();
  915. mHostService.onDiagnosticMessage("tun2socks started");
  916. }
  917. private void stopTun2Socks() {
  918. if (mTun2SocksThread != null) {
  919. try {
  920. terminateTun2Socks();
  921. mTun2SocksThread.join();
  922. } catch (InterruptedException e) {
  923. Thread.currentThread().interrupt();
  924. }
  925. mTun2SocksThread = null;
  926. mHostService.onDiagnosticMessage("tun2socks stopped");
  927. }
  928. }
  929. public static void logTun2Socks(String level, String channel, String msg) {
  930. String logMsg = "tun2socks: " + level + "(" + channel + "): " + msg;
  931. mPsiphonTunnel.mHostService.onDiagnosticMessage(logMsg);
  932. }
  933. private native static int runTun2Socks(
  934. int vpnInterfaceFileDescriptor,
  935. int vpnInterfaceMTU,
  936. String vpnIpAddress,
  937. String vpnNetMask,
  938. String socksServerAddress,
  939. String udpgwServerAddress,
  940. int udpgwTransparentDNS);
  941. private native static int terminateTun2Socks();
  942. private native static int enableUdpGwKeepalive();
  943. private native static int disableUdpGwKeepalive();
  944. //----------------------------------------------------------------------------------------------
  945. // Implementation: Network Utils
  946. //----------------------------------------------------------------------------------------------
  947. private static boolean hasNetworkConnectivity(Context context) {
  948. ConnectivityManager connectivityManager =
  949. (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  950. if (connectivityManager == null) {
  951. return false;
  952. }
  953. NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
  954. return networkInfo != null && networkInfo.isConnected();
  955. }
  956. private static class PrivateAddress {
  957. final public String mIpAddress;
  958. final public String mSubnet;
  959. final public int mPrefixLength;
  960. final public String mRouter;
  961. public PrivateAddress(String ipAddress, String subnet, int prefixLength, String router) {
  962. mIpAddress = ipAddress;
  963. mSubnet = subnet;
  964. mPrefixLength = prefixLength;
  965. mRouter = router;
  966. }
  967. }
  968. private static PrivateAddress selectPrivateAddress() throws Exception {
  969. // Select one of 10.0.0.1, 172.16.0.1, or 192.168.0.1 depending on
  970. // which private address range isn't in use.
  971. Map<String, PrivateAddress> candidates = new HashMap<String, PrivateAddress>();
  972. candidates.put( "10", new PrivateAddress("10.0.0.1", "10.0.0.0", 8, "10.0.0.2"));
  973. candidates.put("172", new PrivateAddress("172.16.0.1", "172.16.0.0", 12, "172.16.0.2"));
  974. candidates.put("192", new PrivateAddress("192.168.0.1", "192.168.0.0", 16, "192.168.0.2"));
  975. candidates.put("169", new PrivateAddress("169.254.1.1", "169.254.1.0", 24, "169.254.1.2"));
  976. List<NetworkInterface> netInterfaces;
  977. try {
  978. netInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
  979. } catch (SocketException e) {
  980. throw new Exception("selectPrivateAddress failed", e);
  981. }
  982. for (NetworkInterface netInterface : netInterfaces) {
  983. for (InetAddress inetAddress : Collections.list(netInterface.getInetAddresses())) {
  984. if (inetAddress instanceof Inet4Address) {
  985. String ipAddress = inetAddress.getHostAddress();
  986. if (ipAddress.startsWith("10.")) {
  987. candidates.remove("10");
  988. }
  989. else if (
  990. ipAddress.length() >= 6 &&
  991. ipAddress.substring(0, 6).compareTo("172.16") >= 0 &&
  992. ipAddress.substring(0, 6).compareTo("172.31") <= 0) {
  993. candidates.remove("172");
  994. }
  995. else if (ipAddress.startsWith("192.168")) {
  996. candidates.remove("192");
  997. }
  998. }
  999. }
  1000. }
  1001. if (candidates.size() > 0) {
  1002. return candidates.values().iterator().next();
  1003. }
  1004. throw new Exception("no private address available");
  1005. }
  1006. public static String getFirstActiveNetworkDnsResolver(Context context)
  1007. throws Exception {
  1008. Collection<InetAddress> dnsResolvers = getActiveNetworkDnsResolvers(context);
  1009. if (!dnsResolvers.isEmpty()) {
  1010. // strip the leading slash e.g., "/192.168.1.1"
  1011. String dnsResolver = dnsResolvers.iterator().next().toString();
  1012. if (dnsResolver.startsWith("/")) {
  1013. dnsResolver = dnsResolver.substring(1);
  1014. }
  1015. return dnsResolver;
  1016. }
  1017. throw new Exception("no active network DNS resolver");
  1018. }
  1019. @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  1020. private static Collection<InetAddress> getActiveNetworkDnsResolvers(Context context)
  1021. throws Exception {
  1022. final String errorMessage = "getActiveNetworkDnsResolvers failed";
  1023. ArrayList<InetAddress> dnsAddresses = new ArrayList<InetAddress>();
  1024. try {
  1025. // Hidden API
  1026. // - only available in Android 4.0+
  1027. // - no guarantee will be available beyond 4.2, or on all vendor devices
  1028. ConnectivityManager connectivityManager =
  1029. (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  1030. Class<?> LinkPropertiesClass = Class.forName("android.net.LinkProperties");
  1031. Method getActiveLinkPropertiesMethod = ConnectivityManager.class.getMethod("getActiveLinkProperties", new Class []{});
  1032. Object linkProperties = getActiveLinkPropertiesMethod.invoke(connectivityManager);
  1033. if (linkProperties != null) {
  1034. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
  1035. Method getDnsesMethod = LinkPropertiesClass.getMethod("getDnses", new Class []{});
  1036. Collection<?> dnses = (Collection<?>)getDnsesMethod.invoke(linkProperties);
  1037. for (Object dns : dnses) {
  1038. dnsAddresses.add((InetAddress)dns);
  1039. }
  1040. } else {
  1041. // LinkProperties is public in API 21 (and the DNS function signature has changed)
  1042. for (InetAddress dns : ((LinkProperties)linkProperties).getDnsServers()) {
  1043. dnsAddresses.add(dns);
  1044. }
  1045. }
  1046. }
  1047. } catch (ClassNotFoundException e) {
  1048. throw new Exception(errorMessage, e);
  1049. } catch (NoSuchMethodException e) {
  1050. throw new Exception(errorMessage, e);
  1051. } catch (IllegalArgumentException e) {
  1052. throw new Exception(errorMessage, e);
  1053. } catch (IllegalAccessException e) {
  1054. throw new Exception(errorMessage, e);
  1055. } catch (InvocationTargetException e) {
  1056. throw new Exception(errorMessage, e);
  1057. } catch (NullPointerException e) {
  1058. throw new Exception(errorMessage, e);
  1059. }
  1060. return dnsAddresses;
  1061. }
  1062. //----------------------------------------------------------------------------------------------
  1063. // Exception
  1064. //----------------------------------------------------------------------------------------------
  1065. public static class Exception extends java.lang.Exception {
  1066. private static final long serialVersionUID = 1L;
  1067. public Exception(String message) {
  1068. super(message);
  1069. }
  1070. public Exception(String message, Throwable cause) {
  1071. super(message + ": " + cause.getMessage());
  1072. }
  1073. }
  1074. }