PsiphonTunnel.java 48 KB

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