blob: c5aedd2900576f09e3a5f85600efd873f9583662 [file] [log] [blame]
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.connectivity;
18
Jeff Sharkey899223b2012-08-04 15:24:58 -070019import static android.Manifest.permission.BIND_VPN_SERVICE;
Paul Jensen0784eea2014-08-19 16:00:24 -040020import static android.os.UserHandle.PER_USER_RANGE;
Lorenzo Colitti50262792014-09-19 01:53:35 +090021import static android.net.RouteInfo.RTN_THROW;
Lorenzo Colitti60446162014-09-20 00:14:31 +090022import static android.net.RouteInfo.RTN_UNREACHABLE;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -070023import static android.system.OsConstants.AF_INET;
24import static android.system.OsConstants.AF_INET6;
Jeff Sharkey899223b2012-08-04 15:24:58 -070025
Jeff Davidsonbc19c182014-11-11 13:20:01 -080026import android.Manifest;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070027import android.app.AppGlobals;
Jeff Davidson05542602014-08-11 14:07:27 -070028import android.app.AppOpsManager;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -070029import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070030import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070031import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070032import android.content.Context;
33import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070034import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070035import android.content.ServiceConnection;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070036import android.content.pm.ApplicationInfo;
37import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040038import android.content.pm.PackageManager.NameNotFoundException;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070039import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070040import android.content.pm.UserInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070041import android.net.ConnectivityManager;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070042import android.net.IConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070043import android.net.INetworkManagementEventObserver;
Lorenzo Colitti50262792014-09-19 01:53:35 +090044import android.net.IpPrefix;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070045import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070046import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070047import android.net.LocalSocket;
48import android.net.LocalSocketAddress;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040049import android.net.NetworkAgent;
50import android.net.NetworkCapabilities;
Jeff Sharkey899223b2012-08-04 15:24:58 -070051import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040052import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070053import android.net.NetworkMisc;
Jeff Sharkey82f85212012-08-24 11:17:25 -070054import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040055import android.net.UidRange;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070056import android.os.Binder;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080057import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070058import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070059import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040060import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070061import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070062import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070063import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070064import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070065import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070066import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070067import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070068import android.os.UserManager;
Jeff Sharkey82f85212012-08-24 11:17:25 -070069import android.security.Credentials;
70import android.security.KeyStore;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070071import android.util.Log;
72
Chad Brubakerc2865192013-07-10 14:46:23 -070073import com.android.internal.annotations.GuardedBy;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070074import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070075import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -070076import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070077import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070078
Jeff Davidson05542602014-08-11 14:07:27 -070079import libcore.io.IoUtils;
80
Chia-chi Yeh97a61562011-07-14 15:05:05 -070081import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070082import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070083import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070084import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070085import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -070086import java.net.Inet6Address;
87import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070088import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040089import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070090import java.util.Arrays;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040091import java.util.List;
Paul Jensen0784eea2014-08-19 16:00:24 -040092import java.util.SortedSet;
93import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070094import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070095
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070096/**
97 * @hide
98 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040099public class Vpn {
100 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700101 private static final String TAG = "Vpn";
102 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400103
Jeff Sharkey899223b2012-08-04 15:24:58 -0700104 // TODO: create separate trackers for each unique VPN to support
105 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700106
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400107 private Context mContext;
108 private NetworkInfo mNetworkInfo;
109 private String mPackage;
110 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700111 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700112 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700113 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700114 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700115 private volatile boolean mEnableTeardown = true;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700116 private final IConnectivityManager mConnService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400117 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700118 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400119 private NetworkAgent mNetworkAgent;
120 private final Looper mLooper;
121 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700122
123 /* list of users using this VPN. */
124 @GuardedBy("this")
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400125 private List<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700126 private BroadcastReceiver mUserIntentReceiver = null;
127
Paul Jensen0784eea2014-08-19 16:00:24 -0400128 // Handle of user initiating VPN.
129 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700130
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400131 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Paul Jensen0784eea2014-08-19 16:00:24 -0400132 IConnectivityManager connService, int userHandle) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700133 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400134 mNetd = netService;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700135 mConnService = connService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400136 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400137 mLooper = looper;
138
139 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400140 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700141
142 try {
143 netService.registerObserver(mObserver);
144 } catch (RemoteException e) {
145 Log.wtf(TAG, "Problem registering observer", e);
146 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400147 if (userHandle == UserHandle.USER_OWNER) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700148 // Owner's VPN also needs to handle restricted users
149 mUserIntentReceiver = new BroadcastReceiver() {
150 @Override
151 public void onReceive(Context context, Intent intent) {
152 final String action = intent.getAction();
Paul Jensen0784eea2014-08-19 16:00:24 -0400153 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Chad Brubakerc2865192013-07-10 14:46:23 -0700154 UserHandle.USER_NULL);
Paul Jensen0784eea2014-08-19 16:00:24 -0400155 if (userHandle == UserHandle.USER_NULL) return;
Chad Brubakerc2865192013-07-10 14:46:23 -0700156
157 if (Intent.ACTION_USER_ADDED.equals(action)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400158 onUserAdded(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700159 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400160 onUserRemoved(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700161 }
162 }
163 };
164
165 IntentFilter intentFilter = new IntentFilter();
166 intentFilter.addAction(Intent.ACTION_USER_ADDED);
167 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
168 mContext.registerReceiverAsUser(
169 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
170 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400171
172 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
173 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
174 mNetworkCapabilities = new NetworkCapabilities();
175 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
176 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700177 }
178
Jeff Sharkey57666932013-04-30 17:01:57 -0700179 /**
Jeff Sharkey57666932013-04-30 17:01:57 -0700180 * Set if this object is responsible for watching for {@link NetworkInfo}
181 * teardown. When {@code false}, teardown is handled externally by someone
182 * else.
183 */
184 public void setEnableTeardown(boolean enableTeardown) {
185 mEnableTeardown = enableTeardown;
186 }
187
Jeff Sharkey899223b2012-08-04 15:24:58 -0700188 /**
189 * Update current state, dispaching event to listeners.
190 */
191 private void updateState(DetailedState detailedState, String reason) {
192 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
193 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400194 if (mNetworkAgent != null) {
195 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
196 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700197 }
198
199 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700200 * Prepare for a VPN application. This method is designed to solve
201 * race conditions. It first compares the current prepared package
202 * with {@code oldPackage}. If they are the same, the prepared
203 * package is revoked and replaced with {@code newPackage}. If
204 * {@code oldPackage} is {@code null}, the comparison is omitted.
205 * If {@code newPackage} is the same package or {@code null}, the
206 * revocation is omitted. This method returns {@code true} if the
207 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700208 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700209 * Legacy VPN is handled specially since it is not a real package.
210 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
211 * it can be revoked by itself.
212 *
213 * @param oldPackage The package name of the old VPN application.
214 * @param newPackage The package name of the new VPN application.
215 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700216 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700217 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidsonbe085872014-10-24 10:35:53 -0700218 if (oldPackage != null && getAppUid(oldPackage, mUserHandle) != mOwnerUID) {
Jeff Davidson11008a72014-11-20 13:12:46 -0800219 // The package doesn't match. We return false (to obtain user consent) unless the user
220 // has already consented to that VPN package.
Jeff Davidson05542602014-08-11 14:07:27 -0700221 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
Jeff Davidson11008a72014-11-20 13:12:46 -0800222 prepareInternal(oldPackage);
Jeff Davidson05542602014-08-11 14:07:27 -0700223 return true;
224 }
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700225 return false;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700226 }
227
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700228 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700229 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
230 getAppUid(newPackage, mUserHandle) == mOwnerUID)) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700231 return true;
232 }
233
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700234 // Check if the caller is authorized.
235 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700236
Jeff Davidson11008a72014-11-20 13:12:46 -0800237 prepareInternal(newPackage);
238 return true;
239 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700240
Jeff Davidson11008a72014-11-20 13:12:46 -0800241 /** Prepare the VPN for the given package. Does not perform permission checks. */
242 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400243 long token = Binder.clearCallingIdentity();
244 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800245 // Reset the interface.
246 if (mInterface != null) {
247 mStatusIntent = null;
248 agentDisconnect();
249 jniReset(mInterface);
250 mInterface = null;
251 mVpnUsers = null;
252 }
253
254 // Revoke the connection or stop LegacyVpnRunner.
255 if (mConnection != null) {
256 try {
257 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
258 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
259 } catch (Exception e) {
260 // ignore
261 }
262 mContext.unbindService(mConnection);
263 mConnection = null;
264 } else if (mLegacyVpnRunner != null) {
265 mLegacyVpnRunner.exit();
266 mLegacyVpnRunner = null;
267 }
268
269 try {
270 mNetd.denyProtect(mOwnerUID);
271 } catch (Exception e) {
272 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
273 }
274
275 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
276 mPackage = newPackage;
277 mOwnerUID = getAppUid(newPackage, mUserHandle);
278 try {
279 mNetd.allowProtect(mOwnerUID);
280 } catch (Exception e) {
281 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
282 }
283 mConfig = null;
284
285 updateState(DetailedState.IDLE, "prepare");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400286 } finally {
287 Binder.restoreCallingIdentity(token);
288 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700289 }
290
Jeff Davidson05542602014-08-11 14:07:27 -0700291 /**
292 * Set whether the current package has the ability to launch VPNs without user intervention.
293 */
294 public void setPackageAuthorization(boolean authorized) {
295 // Check if the caller is authorized.
296 enforceControlPermission();
297
298 if (mPackage == null || VpnConfig.LEGACY_VPN.equals(mPackage)) {
299 return;
300 }
301
302 long token = Binder.clearCallingIdentity();
303 try {
304 AppOpsManager appOps =
305 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
306 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, mOwnerUID, mPackage,
307 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
308 } catch (Exception e) {
309 Log.wtf(TAG, "Failed to set app ops for package " + mPackage, e);
310 } finally {
311 Binder.restoreCallingIdentity(token);
312 }
313 }
314
315 private boolean isVpnUserPreConsented(String packageName) {
316 AppOpsManager appOps =
317 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
318
319 // Verify that the caller matches the given package and has permission to activate VPNs.
320 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
321 packageName) == AppOpsManager.MODE_ALLOWED;
322 }
323
Paul Jensen0784eea2014-08-19 16:00:24 -0400324 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700325 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400326 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700327 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400328 PackageManager pm = mContext.getPackageManager();
329 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700330 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400331 result = pm.getPackageUid(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400332 } catch (NameNotFoundException e) {
333 result = -1;
334 }
335 return result;
336 }
337
338 public NetworkInfo getNetworkInfo() {
339 return mNetworkInfo;
340 }
341
Lorenzo Colitti60446162014-09-20 00:14:31 +0900342 private LinkProperties makeLinkProperties() {
343 boolean allowIPv4 = mConfig.allowIPv4;
344 boolean allowIPv6 = mConfig.allowIPv6;
345
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400346 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900347
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400348 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700349
Lorenzo Colitti60446162014-09-20 00:14:31 +0900350 if (mConfig.addresses != null) {
351 for (LinkAddress address : mConfig.addresses) {
352 lp.addLinkAddress(address);
353 allowIPv4 |= address.getAddress() instanceof Inet4Address;
354 allowIPv6 |= address.getAddress() instanceof Inet6Address;
355 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400356 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900357
358 if (mConfig.routes != null) {
359 for (RouteInfo route : mConfig.routes) {
360 lp.addRoute(route);
361 InetAddress address = route.getDestination().getAddress();
362 allowIPv4 |= address instanceof Inet4Address;
363 allowIPv6 |= address instanceof Inet6Address;
364 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400365 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700366
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400367 if (mConfig.dnsServers != null) {
368 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700369 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
370 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900371 allowIPv4 |= address instanceof Inet4Address;
372 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400373 }
374 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700375
Lorenzo Colitti60446162014-09-20 00:14:31 +0900376 if (!allowIPv4) {
377 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
378 }
379 if (!allowIPv6) {
380 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
381 }
382
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400383 // Concatenate search domains into a string.
384 StringBuilder buffer = new StringBuilder();
385 if (mConfig.searchDomains != null) {
386 for (String domain : mConfig.searchDomains) {
387 buffer.append(domain).append(' ');
388 }
389 }
390 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700391
Lorenzo Colitti60446162014-09-20 00:14:31 +0900392 // TODO: Stop setting the MTU in jniCreate and set it here.
393
394 return lp;
395 }
396
397 private void agentConnect() {
398 LinkProperties lp = makeLinkProperties();
399
400 if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
401 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
402 } else {
403 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
404 }
405
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400406 mNetworkInfo.setIsAvailable(true);
407 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700408
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700409 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700410 networkMisc.allowBypass = mConfig.allowBypass;
411
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400412 long token = Binder.clearCallingIdentity();
413 try {
414 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700415 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700416 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400417 public void unwanted() {
418 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700419 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400420 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700421 } finally {
422 Binder.restoreCallingIdentity(token);
423 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700424
Paul Jensen0784eea2014-08-19 16:00:24 -0400425 addVpnUserLocked(mUserHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400426 // If we are owner assign all Restricted Users to this VPN
Paul Jensen0784eea2014-08-19 16:00:24 -0400427 if (mUserHandle == UserHandle.USER_OWNER) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400428 token = Binder.clearCallingIdentity();
429 List<UserInfo> users;
430 try {
431 users = UserManager.get(mContext).getUsers();
432 } finally {
433 Binder.restoreCallingIdentity(token);
434 }
435 for (UserInfo user : users) {
436 if (user.isRestricted()) {
437 addVpnUserLocked(user.id);
438 }
439 }
440 }
441 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
442 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700443
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400444 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
445 networkInfo.setIsAvailable(false);
446 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
447 if (networkAgent != null) {
448 networkAgent.sendNetworkInfo(networkInfo);
449 }
450 }
451
452 private void agentDisconnect(NetworkAgent networkAgent) {
453 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
454 agentDisconnect(networkInfo, networkAgent);
455 }
456
457 private void agentDisconnect() {
458 if (mNetworkInfo.isConnected()) {
459 agentDisconnect(mNetworkInfo, mNetworkAgent);
460 mNetworkAgent = null;
461 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700462 }
463
464 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700465 * Establish a VPN network and return the file descriptor of the VPN
466 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700467 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700468 *
469 * @param config The parameters to configure the network.
470 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700471 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700472 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700473 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700474 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400475 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700476 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700477 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700478 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700479 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
480 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700481 long token = Binder.clearCallingIdentity();
482 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700483 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400484 UserInfo user = mgr.getUserInfo(mUserHandle);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400485 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700486 throw new SecurityException("Restricted users cannot establish VPNs");
487 }
488
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700489 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400490 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700491 if (info == null) {
492 throw new SecurityException("Cannot find " + config.user);
493 }
494 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
495 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
496 }
497 } catch (RemoteException e) {
498 throw new SecurityException("Cannot find " + config.user);
499 } finally {
500 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700501 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700502
Chad Brubaker850eb672014-03-21 21:02:47 +0000503 // Save the old config in case we need to go back.
504 VpnConfig oldConfig = mConfig;
505 String oldInterface = mInterface;
506 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400507 NetworkAgent oldNetworkAgent = mNetworkAgent;
508 mNetworkAgent = null;
509 List<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000510
Chia-chi Yehe9107902011-07-02 01:48:50 -0700511 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700512 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700513 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700514 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700515 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700516
Chad Brubakerc2865192013-07-10 14:46:23 -0700517 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700518 StringBuilder builder = new StringBuilder();
519 for (LinkAddress address : config.addresses) {
520 builder.append(" " + address);
521 }
522 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700523 throw new IllegalArgumentException("At least one address must be specified");
524 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700525 Connection connection = new Connection();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700526 if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
Paul Jensen0784eea2014-08-19 16:00:24 -0400527 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700528 throw new IllegalStateException("Cannot bind " + config.user);
529 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000530
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700531 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700532 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700533
534 // Fill more values.
535 config.user = mPackage;
536 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700537 config.startTime = SystemClock.elapsedRealtime();
538 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000539
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700540 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400541 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700542
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400543 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000544
545 if (oldConnection != null) {
546 mContext.unbindService(oldConnection);
547 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400548 // Remove the old tun's user forwarding rules
549 // The new tun's user rules have already been added so they will take over
550 // as rules are deleted. This prevents data leakage as the rules are moved over.
551 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000552 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000553 jniReset(oldInterface);
554 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700555
556 try {
557 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
558 } catch (IOException e) {
559 throw new IllegalStateException(
560 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
561 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000562 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000563 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400564 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000565 // restore old state
566 mConfig = oldConfig;
567 mConnection = oldConnection;
568 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400569 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000570 mInterface = oldInterface;
571 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700572 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000573 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700574 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700575 }
576
Chad Brubakerc2865192013-07-10 14:46:23 -0700577 private boolean isRunningLocked() {
578 return mVpnUsers != null;
579 }
580
Paul Jensen0784eea2014-08-19 16:00:24 -0400581 // Note: Return type guarantees results are deduped and sorted, which callers require.
582 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
583 SortedSet<Integer> uids = new TreeSet<Integer>();
584 for (String app : packageNames) {
585 int uid = getAppUid(app, userHandle);
586 if (uid != -1) uids.add(uid);
587 }
588 return uids;
589 }
590
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400591 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Paul Jensen0784eea2014-08-19 16:00:24 -0400592 private void addVpnUserLocked(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700593 if (!isRunningLocked()) {
594 throw new IllegalStateException("VPN is not active");
595 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700596
Paul Jensen0784eea2014-08-19 16:00:24 -0400597 if (mConfig.allowedApplications != null) {
598 // Add ranges covering all UIDs for allowedApplications.
599 int start = -1, stop = -1;
600 for (int uid : getAppsUids(mConfig.allowedApplications, userHandle)) {
601 if (start == -1) {
602 start = uid;
603 } else if (uid != stop + 1) {
604 mVpnUsers.add(new UidRange(start, stop));
605 start = uid;
606 }
607 stop = uid;
608 }
609 if (start != -1) mVpnUsers.add(new UidRange(start, stop));
610 } else if (mConfig.disallowedApplications != null) {
611 // Add all ranges for user skipping UIDs for disallowedApplications.
612 final UidRange userRange = UidRange.createForUser(userHandle);
613 int start = userRange.start;
614 for (int uid : getAppsUids(mConfig.disallowedApplications, userHandle)) {
615 if (uid == start) {
616 start++;
617 } else {
618 mVpnUsers.add(new UidRange(start, uid - 1));
619 start = uid + 1;
620 }
621 }
622 if (start <= userRange.stop) mVpnUsers.add(new UidRange(start, userRange.stop));
623 } else {
624 // Add all UIDs for the user.
625 mVpnUsers.add(UidRange.createForUser(userHandle));
626 }
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700627
628 prepareStatusIntent();
Chad Brubakerc2865192013-07-10 14:46:23 -0700629 }
630
Paul Jensen0784eea2014-08-19 16:00:24 -0400631 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
632 // apply to userHandle.
633 private List<UidRange> uidRangesForUser(int userHandle) {
634 final UidRange userRange = UidRange.createForUser(userHandle);
635 final List<UidRange> ranges = new ArrayList<UidRange>();
636 for (UidRange range : mVpnUsers) {
637 if (range.start >= userRange.start && range.stop <= userRange.stop) {
638 ranges.add(range);
639 }
640 }
641 return ranges;
642 }
643
644 private void removeVpnUserLocked(int userHandle) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700645 if (!isRunningLocked()) {
646 throw new IllegalStateException("VPN is not active");
647 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400648 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700649 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400650 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700651 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400652 mVpnUsers.removeAll(ranges);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700653 mStatusIntent = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700654 }
655
Paul Jensen0784eea2014-08-19 16:00:24 -0400656 private void onUserAdded(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700657 // If the user is restricted tie them to the owner's VPN
658 synchronized(Vpn.this) {
659 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400660 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700661 if (user.isRestricted()) {
662 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400663 addVpnUserLocked(userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400664 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400665 final List<UidRange> ranges = uidRangesForUser(userHandle);
666 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400667 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700668 } catch (Exception e) {
669 Log.wtf(TAG, "Failed to add restricted user to owner", e);
670 }
671 }
672 }
673 }
674
Paul Jensen0784eea2014-08-19 16:00:24 -0400675 private void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700676 // clean up if restricted
677 synchronized(Vpn.this) {
678 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400679 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700680 if (user.isRestricted()) {
681 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400682 removeVpnUserLocked(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700683 } catch (Exception e) {
684 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
685 }
686 }
687 }
688 }
689
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700690 /**
691 * Return the configuration of the currently running VPN.
692 */
693 public VpnConfig getVpnConfig() {
694 enforceControlPermission();
695 return mConfig;
696 }
697
Jeff Sharkey899223b2012-08-04 15:24:58 -0700698 @Deprecated
699 public synchronized void interfaceStatusChanged(String iface, boolean up) {
700 try {
701 mObserver.interfaceStatusChanged(iface, up);
702 } catch (RemoteException e) {
703 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700704 }
705 }
706
Jeff Sharkey899223b2012-08-04 15:24:58 -0700707 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
708 @Override
709 public void interfaceStatusChanged(String interfaze, boolean up) {
710 synchronized (Vpn.this) {
711 if (!up && mLegacyVpnRunner != null) {
712 mLegacyVpnRunner.check(interfaze);
713 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700714 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700715 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700716
Jeff Sharkey899223b2012-08-04 15:24:58 -0700717 @Override
718 public void interfaceRemoved(String interfaze) {
719 synchronized (Vpn.this) {
720 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700721 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400722 mVpnUsers = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700723 mInterface = null;
724 if (mConnection != null) {
725 mContext.unbindService(mConnection);
726 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400727 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700728 } else if (mLegacyVpnRunner != null) {
729 mLegacyVpnRunner.exit();
730 mLegacyVpnRunner = null;
731 }
732 }
733 }
734 }
735 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700736
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700737 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -0800738 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700739 }
740
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700741 private class Connection implements ServiceConnection {
742 private IBinder mService;
743
744 @Override
745 public void onServiceConnected(ComponentName name, IBinder service) {
746 mService = service;
747 }
748
749 @Override
750 public void onServiceDisconnected(ComponentName name) {
751 mService = null;
752 }
753 }
754
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700755 private void prepareStatusIntent() {
756 final long token = Binder.clearCallingIdentity();
757 try {
758 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
759 } finally {
760 Binder.restoreCallingIdentity(token);
761 }
762 }
763
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700764 public synchronized boolean addAddress(String address, int prefixLength) {
765 if (Binder.getCallingUid() != mOwnerUID || mInterface == null || mNetworkAgent == null) {
766 return false;
767 }
768 boolean success = jniAddAddress(mInterface, address, prefixLength);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900769 if (mNetworkAgent != null) {
770 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700771 }
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700772 return success;
773 }
774
775 public synchronized boolean removeAddress(String address, int prefixLength) {
776 if (Binder.getCallingUid() != mOwnerUID || mInterface == null || mNetworkAgent == null) {
777 return false;
778 }
779 boolean success = jniDelAddress(mInterface, address, prefixLength);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900780 if (mNetworkAgent != null) {
781 mNetworkAgent.sendLinkProperties(makeLinkProperties());
782 }
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700783 return success;
784 }
785
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700786 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700787 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700788 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700789 private native void jniReset(String interfaze);
790 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700791 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
792 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700793
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900794 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
795 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700796 // Currently legacy VPN only works on IPv4.
797 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900798 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700799 }
800 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700801
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900802 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700803 }
804
805 /**
806 * Start legacy VPN, controlling native daemons as needed. Creates a
807 * secondary thread to perform connection work, returning quickly.
808 */
809 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800810 enforceControlPermission();
Kenny Rootb9594ce2013-02-14 10:18:38 -0800811 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700812 throw new IllegalStateException("KeyStore isn't unlocked");
813 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400814 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400815 UserInfo user = mgr.getUserInfo(mUserHandle);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400816 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
817 throw new SecurityException("Restricted users cannot establish VPNs");
818 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700819
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900820 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
821 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
822 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700823
824 // Load certificates.
825 String privateKey = "";
826 String userCert = "";
827 String caCert = "";
828 String serverCert = "";
829 if (!profile.ipsecUserCert.isEmpty()) {
830 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
831 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700832 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700833 }
834 if (!profile.ipsecCaCert.isEmpty()) {
835 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700836 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700837 }
838 if (!profile.ipsecServerCert.isEmpty()) {
839 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700840 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700841 }
842 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
843 throw new IllegalStateException("Cannot load credentials");
844 }
845
846 // Prepare arguments for racoon.
847 String[] racoon = null;
848 switch (profile.type) {
849 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
850 racoon = new String[] {
851 iface, profile.server, "udppsk", profile.ipsecIdentifier,
852 profile.ipsecSecret, "1701",
853 };
854 break;
855 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
856 racoon = new String[] {
857 iface, profile.server, "udprsa", privateKey, userCert,
858 caCert, serverCert, "1701",
859 };
860 break;
861 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
862 racoon = new String[] {
863 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
864 profile.ipsecSecret, profile.username, profile.password, "", gateway,
865 };
866 break;
867 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
868 racoon = new String[] {
869 iface, profile.server, "xauthrsa", privateKey, userCert,
870 caCert, serverCert, profile.username, profile.password, "", gateway,
871 };
872 break;
873 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
874 racoon = new String[] {
875 iface, profile.server, "hybridrsa",
876 caCert, serverCert, profile.username, profile.password, "", gateway,
877 };
878 break;
879 }
880
881 // Prepare arguments for mtpd.
882 String[] mtpd = null;
883 switch (profile.type) {
884 case VpnProfile.TYPE_PPTP:
885 mtpd = new String[] {
886 iface, "pptp", profile.server, "1723",
887 "name", profile.username, "password", profile.password,
888 "linkname", "vpn", "refuse-eap", "nodefaultroute",
889 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
890 (profile.mppe ? "+mppe" : "nomppe"),
891 };
892 break;
893 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
894 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
895 mtpd = new String[] {
896 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
897 "name", profile.username, "password", profile.password,
898 "linkname", "vpn", "refuse-eap", "nodefaultroute",
899 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
900 };
901 break;
902 }
903
904 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700905 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700906 config.user = profile.key;
907 config.interfaze = iface;
908 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700909
910 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700911 if (!profile.dnsServers.isEmpty()) {
912 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
913 }
914 if (!profile.searchDomains.isEmpty()) {
915 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
916 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700917 startLegacyVpn(config, racoon, mtpd);
918 }
919
920 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
921 stopLegacyVpn();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700922
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700923 // Prepare for the new request. This also checks the caller.
924 prepare(null, VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700925 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700926
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700927 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700928 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
929 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700930 }
931
Jeff Sharkey899223b2012-08-04 15:24:58 -0700932 public synchronized void stopLegacyVpn() {
933 if (mLegacyVpnRunner != null) {
934 mLegacyVpnRunner.exit();
935 mLegacyVpnRunner = null;
936
937 synchronized (LegacyVpnRunner.TAG) {
938 // wait for old thread to completely finish before spinning up
939 // new instance, otherwise state updates can be out of order.
940 }
941 }
942 }
943
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700944 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700945 * Return the information of the current ongoing legacy VPN.
946 */
947 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700948 // Check if the caller is authorized.
949 enforceControlPermission();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700950 if (mLegacyVpnRunner == null) return null;
951
952 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -0700953 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700954 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700955 if (mNetworkInfo.isConnected()) {
956 info.intent = mStatusIntent;
957 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700958 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700959 }
960
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700961 public VpnConfig getLegacyVpnConfig() {
962 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700963 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700964 } else {
965 return null;
966 }
967 }
968
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700969 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700970 * Bringing up a VPN connection takes time, and that is all this thread
971 * does. Here we have plenty of time. The only thing we need to take
972 * care of is responding to interruptions as soon as possible. Otherwise
973 * requests will be piled up. This can be done in a Handler as a state
974 * machine, but it is much easier to read in the current form.
975 */
976 private class LegacyVpnRunner extends Thread {
977 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700978
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700979 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700980 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700981 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700982 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700983 private final AtomicInteger mOuterConnection =
984 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700985
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700986 private long mTimer = -1;
987
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700988 /**
989 * Watch for the outer connection (passing in the constructor) going away.
990 */
991 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
992 @Override
993 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -0700994 if (!mEnableTeardown) return;
995
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700996 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
997 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
998 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
999 NetworkInfo info = (NetworkInfo)intent.getExtra(
1000 ConnectivityManager.EXTRA_NETWORK_INFO);
1001 if (info != null && !info.isConnectedOrConnecting()) {
1002 try {
1003 mObserver.interfaceStatusChanged(mOuterInterface, false);
1004 } catch (RemoteException e) {}
1005 }
1006 }
1007 }
1008 }
1009 };
1010
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001011 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001012 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001013 mConfig = config;
1014 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001015 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001016 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001017 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001018
1019 // This is the interface which VPN is running on,
1020 // mConfig.interfaze will change to point to OUR
1021 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001022 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001023 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001024 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001025 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001026
1027 try {
1028 mOuterConnection.set(
1029 mConnService.findConnectionTypeForIface(mOuterInterface));
1030 } catch (Exception e) {
1031 mOuterConnection.set(ConnectivityManager.TYPE_NONE);
1032 }
1033
1034 IntentFilter filter = new IntentFilter();
1035 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1036 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001037 }
1038
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001039 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001040 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001041 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1042 exit();
1043 }
1044 }
1045
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001046 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001047 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001048 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001049 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001050 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001051 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001052 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001053 try {
1054 mContext.unregisterReceiver(mBroadcastReceiver);
1055 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001056 }
1057
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001058 @Override
1059 public void run() {
1060 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001061 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001062 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001063 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001064 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001065 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001066 }
1067 }
1068
1069 private void checkpoint(boolean yield) throws InterruptedException {
1070 long now = SystemClock.elapsedRealtime();
1071 if (mTimer == -1) {
1072 mTimer = now;
1073 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001074 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001075 Thread.sleep(yield ? 200 : 1);
1076 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001077 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001078 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001079 }
1080 }
1081
1082 private void execute() {
1083 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001084 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001085 try {
1086 // Initialize the timer.
1087 checkpoint(false);
1088
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001089 // Wait for the daemons to stop.
1090 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001091 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001092 checkpoint(true);
1093 }
1094 }
1095
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001096 // Clear the previous state.
1097 File state = new File("/data/misc/vpn/state");
1098 state.delete();
1099 if (state.exists()) {
1100 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001101 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001102 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001103 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001104
Chia-chi Yehe9107902011-07-02 01:48:50 -07001105 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001106 boolean restart = false;
1107 for (String[] arguments : mArguments) {
1108 restart = restart || (arguments != null);
1109 }
1110 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001111 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001112 return;
1113 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001114 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001115
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001116 // Start the daemon with arguments.
1117 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001118 String[] arguments = mArguments[i];
1119 if (arguments == null) {
1120 continue;
1121 }
1122
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001123 // Start the daemon.
1124 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001125 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001126
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001127 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001128 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001129 checkpoint(true);
1130 }
1131
1132 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001133 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001134 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001135 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001136
1137 // Wait for the socket to connect.
1138 while (true) {
1139 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001140 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001141 break;
1142 } catch (Exception e) {
1143 // ignore
1144 }
1145 checkpoint(true);
1146 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001147 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001148
1149 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001150 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001151 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001152 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001153 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001154 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001155 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001156 out.write(bytes.length >> 8);
1157 out.write(bytes.length);
1158 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001159 checkpoint(false);
1160 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001161 out.write(0xFF);
1162 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001163 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001164
1165 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001166 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001167 while (true) {
1168 try {
1169 if (in.read() == -1) {
1170 break;
1171 }
1172 } catch (Exception e) {
1173 // ignore
1174 }
1175 checkpoint(true);
1176 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001177 }
1178
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001179 // Wait for the daemons to create the new state.
1180 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001181 // Check if a running daemon is dead.
1182 for (int i = 0; i < mDaemons.length; ++i) {
1183 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001184 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001185 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001186 }
1187 }
1188 checkpoint(true);
1189 }
1190
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001191 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001192 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001193 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001194 throw new IllegalStateException("Cannot parse the state");
1195 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001196
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001197 // Set the interface and the addresses in the config.
1198 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001199
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001200 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001201 // Set the routes if they are not set in the config.
1202 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001203 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001204 }
1205
1206 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001207 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001208 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001209 if (!dnsServers.isEmpty()) {
1210 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1211 }
1212 }
1213
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001214 // Set the search domains if they are not set in the config.
1215 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1216 String searchDomains = parameters[4].trim();
1217 if (!searchDomains.isEmpty()) {
1218 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1219 }
1220 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001221
Lorenzo Colitti50262792014-09-19 01:53:35 +09001222 // Add a throw route for the VPN server endpoint, if one was specified.
1223 String endpoint = parameters[5];
1224 if (!endpoint.isEmpty()) {
1225 try {
1226 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1227 if (addr instanceof Inet4Address) {
1228 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1229 } else if (addr instanceof Inet6Address) {
1230 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1231 } else {
1232 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1233 }
1234 } catch (IllegalArgumentException e) {
1235 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1236 }
1237 }
1238
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001239 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001240 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001241 // Set the start time
1242 mConfig.startTime = SystemClock.elapsedRealtime();
1243
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001244 // Check if the thread is interrupted while we are waiting.
1245 checkpoint(false);
1246
Chia-chi Yehe9107902011-07-02 01:48:50 -07001247 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001248 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001249 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001250 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001251
1252 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001253 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001254 mVpnUsers = new ArrayList<UidRange>();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001255
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001256 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001257
1258 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001259 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001260 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001261 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001262 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001263 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001264 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001265 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001266 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001267 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001268 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001269 }
1270 }
1271
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001272 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001273 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001274 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001275 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001276 }
1277 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001278
1279 /**
1280 * Monitor the daemons we started, moving to disconnected state if the
1281 * underlying services fail.
1282 */
1283 private void monitorDaemons() {
1284 if (!mNetworkInfo.isConnected()) {
1285 return;
1286 }
1287
1288 try {
1289 while (true) {
1290 Thread.sleep(2000);
1291 for (int i = 0; i < mDaemons.length; i++) {
1292 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1293 return;
1294 }
1295 }
1296 }
1297 } catch (InterruptedException e) {
1298 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1299 } finally {
1300 for (String daemon : mDaemons) {
1301 SystemService.stop(daemon);
1302 }
1303
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001304 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001305 }
1306 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001307 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001308}