PsiphonTunnel.java 47 KB

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