blob: 32b9429ae6561321ae9ad4b1a1e9a97af9af77b2 [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 Jensen31a94f42015-02-13 14:18:39 -050020import static android.net.ConnectivityManager.NETID_UNSET;
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;
Jeff Sharkey899223b2012-08-04 15:24:58 -070023
Jeff Davidsonbc19c182014-11-11 13:20:01 -080024import android.Manifest;
Robin Lee4d03abc2016-05-09 12:32:27 +010025import android.annotation.NonNull;
26import android.annotation.Nullable;
27import android.annotation.UserIdInt;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070028import android.app.AppGlobals;
Jeff Davidson05542602014-08-11 14:07:27 -070029import android.app.AppOpsManager;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -070030import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070031import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070032import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070033import android.content.Context;
34import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070035import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070036import android.content.ServiceConnection;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070037import 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;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070042import android.net.INetworkManagementEventObserver;
Lorenzo Colitti50262792014-09-19 01:53:35 +090043import android.net.IpPrefix;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070044import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070045import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070046import android.net.LocalSocket;
47import android.net.LocalSocketAddress;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -080048import android.net.Network;
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;
Paul Jensene75b9e32015-04-06 11:54:53 -040071import android.text.TextUtils;
Robin Lee4d03abc2016-05-09 12:32:27 +010072import android.util.ArraySet;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070073import android.util.Log;
74
Chad Brubakerc2865192013-07-10 14:46:23 -070075import com.android.internal.annotations.GuardedBy;
Robin Lee4d03abc2016-05-09 12:32:27 +010076import com.android.internal.annotations.VisibleForTesting;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070077import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070078import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080079import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -070080import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070081import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070082
Jeff Davidson05542602014-08-11 14:07:27 -070083import libcore.io.IoUtils;
84
Chia-chi Yeh97a61562011-07-14 15:05:05 -070085import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070086import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070087import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070088import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070089import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -070090import java.net.Inet6Address;
91import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070092import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040093import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070094import java.util.Arrays;
Robin Lee4d03abc2016-05-09 12:32:27 +010095import java.util.Collection;
96import java.util.Collections;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040097import java.util.List;
Robin Lee4d03abc2016-05-09 12:32:27 +010098import java.util.Set;
Paul Jensen0784eea2014-08-19 16:00:24 -040099import java.util.SortedSet;
100import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700101import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700102
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700103/**
104 * @hide
105 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400106public class Vpn {
107 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700108 private static final String TAG = "Vpn";
109 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400110
Jeff Sharkey899223b2012-08-04 15:24:58 -0700111 // TODO: create separate trackers for each unique VPN to support
112 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700113
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400114 private Context mContext;
115 private NetworkInfo mNetworkInfo;
116 private String mPackage;
117 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700118 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700119 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700120 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700121 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700122 private volatile boolean mEnableTeardown = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400123 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700124 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400125 private NetworkAgent mNetworkAgent;
126 private final Looper mLooper;
127 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700128
Robin Lee4d03abc2016-05-09 12:32:27 +0100129 /**
Robin Lee17e61832016-05-09 13:46:28 +0100130 * Whether to keep the connection active after rebooting, or upgrading or reinstalling. This
131 * only applies to {@link VpnService} connections.
132 */
133 private boolean mAlwaysOn = false;
134
135 /**
136 * Whether to disable traffic outside of this VPN even when the VPN is not connected. System
137 * apps can still bypass by choosing explicit networks. Has no effect if {@link mAlwaysOn} is
138 * not set.
139 */
140 private boolean mLockdown = false;
141
142 /**
Robin Lee4d03abc2016-05-09 12:32:27 +0100143 * List of UIDs that are set to use this VPN by default. Normally, every UID in the user is
144 * added to this set but that can be changed by adding allowed or disallowed applications. It
145 * is non-null iff the VPN is connected.
146 *
147 * Unless the VPN has set allowBypass=true, these UIDs are forced into the VPN.
148 *
149 * @see VpnService.Builder#addAllowedApplication(String)
150 * @see VpnService.Builder#addDisallowedApplication(String)
151 */
Chad Brubakerc2865192013-07-10 14:46:23 -0700152 @GuardedBy("this")
Robin Lee4d03abc2016-05-09 12:32:27 +0100153 private Set<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700154
Robin Lee17e61832016-05-09 13:46:28 +0100155 /**
156 * List of UIDs for which networking should be blocked until VPN is ready, during brief periods
157 * when VPN is not running. For example, during system startup or after a crash.
158 * @see mLockdown
159 */
160 @GuardedBy("this")
161 private Set<UidRange> mBlockedUsers = new ArraySet<>();
162
Paul Jensen0784eea2014-08-19 16:00:24 -0400163 // Handle of user initiating VPN.
164 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700165
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400166 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Paul Jensene75b9e32015-04-06 11:54:53 -0400167 int userHandle) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700168 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400169 mNetd = netService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400170 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400171 mLooper = looper;
172
173 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400174 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700175
176 try {
177 netService.registerObserver(mObserver);
178 } catch (RemoteException e) {
179 Log.wtf(TAG, "Problem registering observer", e);
180 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400181
182 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
183 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
184 mNetworkCapabilities = new NetworkCapabilities();
185 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
186 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700187 }
188
Jeff Sharkey57666932013-04-30 17:01:57 -0700189 /**
Jeff Sharkey57666932013-04-30 17:01:57 -0700190 * Set if this object is responsible for watching for {@link NetworkInfo}
191 * teardown. When {@code false}, teardown is handled externally by someone
192 * else.
193 */
194 public void setEnableTeardown(boolean enableTeardown) {
195 mEnableTeardown = enableTeardown;
196 }
197
Jeff Sharkey899223b2012-08-04 15:24:58 -0700198 /**
199 * Update current state, dispaching event to listeners.
200 */
201 private void updateState(DetailedState detailedState, String reason) {
202 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
203 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400204 if (mNetworkAgent != null) {
205 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
206 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700207 }
208
209 /**
Robin Lee244ce8e2016-01-05 18:03:46 +0000210 * Configures an always-on VPN connection through a specific application.
211 * This connection is automatically granted and persisted after a reboot.
212 *
213 * <p>The designated package should exist and declare a {@link VpnService} in its
214 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
215 * otherwise the call will fail.
216 *
Robin Lee17e61832016-05-09 13:46:28 +0100217 * @param packageName the package to designate as always-on VPN supplier.
218 * @param lockdown whether to prevent traffic outside of a VPN, for example while connecting.
Robin Lee244ce8e2016-01-05 18:03:46 +0000219 */
Robin Lee17e61832016-05-09 13:46:28 +0100220 public synchronized boolean setAlwaysOnPackage(String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +0000221 enforceControlPermissionOrInternalCaller();
222
223 // Disconnect current VPN.
224 prepareInternal(VpnConfig.LEGACY_VPN);
225
226 // Pre-authorize new always-on VPN package.
227 if (packageName != null) {
228 if (!setPackageAuthorization(packageName, true)) {
229 return false;
230 }
Robin Lee78378842016-02-12 11:51:33 +0000231 prepareInternal(packageName);
Robin Lee244ce8e2016-01-05 18:03:46 +0000232 }
233
Robin Lee17e61832016-05-09 13:46:28 +0100234 mAlwaysOn = (packageName != null);
235 mLockdown = (mAlwaysOn && lockdown);
236 setVpnForcedLocked(mLockdown);
Robin Lee244ce8e2016-01-05 18:03:46 +0000237 return true;
238 }
239
240 /**
241 * @return the package name of the VPN controller responsible for always-on VPN,
242 * or {@code null} if none is set or always-on VPN is controlled through
243 * lockdown instead.
244 * @hide
245 */
246 public synchronized String getAlwaysOnPackage() {
247 enforceControlPermissionOrInternalCaller();
Robin Lee17e61832016-05-09 13:46:28 +0100248 return (mAlwaysOn ? mPackage : null);
Robin Lee244ce8e2016-01-05 18:03:46 +0000249 }
250
251 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700252 * Prepare for a VPN application. This method is designed to solve
253 * race conditions. It first compares the current prepared package
254 * with {@code oldPackage}. If they are the same, the prepared
255 * package is revoked and replaced with {@code newPackage}. If
256 * {@code oldPackage} is {@code null}, the comparison is omitted.
257 * If {@code newPackage} is the same package or {@code null}, the
258 * revocation is omitted. This method returns {@code true} if the
259 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700260 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700261 * Legacy VPN is handled specially since it is not a real package.
262 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
263 * it can be revoked by itself.
264 *
265 * @param oldPackage The package name of the old VPN application.
266 * @param newPackage The package name of the new VPN application.
267 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700268 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700269 public synchronized boolean prepare(String oldPackage, String newPackage) {
Robin Lee17e61832016-05-09 13:46:28 +0100270 // Stop an existing always-on VPN from being dethroned by other apps.
271 if (mAlwaysOn && !TextUtils.equals(mPackage, newPackage)) {
272 return false;
273 }
274
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700275 if (oldPackage != null) {
276 if (getAppUid(oldPackage, mUserHandle) != mOwnerUID) {
277 // The package doesn't match. We return false (to obtain user consent) unless the
278 // user has already consented to that VPN package.
279 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
280 prepareInternal(oldPackage);
281 return true;
282 }
283 return false;
284 } else if (!oldPackage.equals(VpnConfig.LEGACY_VPN)
285 && !isVpnUserPreConsented(oldPackage)) {
286 // Currently prepared VPN is revoked, so unprepare it and return false.
287 prepareInternal(VpnConfig.LEGACY_VPN);
288 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700289 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700290 }
291
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700292 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700293 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
294 getAppUid(newPackage, mUserHandle) == mOwnerUID)) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700295 return true;
296 }
297
Robin Lee1b1bcd72016-02-12 18:11:30 +0000298 // Check that the caller is authorized.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700299 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700300
Jeff Davidson11008a72014-11-20 13:12:46 -0800301 prepareInternal(newPackage);
302 return true;
303 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700304
Jeff Davidson11008a72014-11-20 13:12:46 -0800305 /** Prepare the VPN for the given package. Does not perform permission checks. */
306 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400307 long token = Binder.clearCallingIdentity();
308 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800309 // Reset the interface.
310 if (mInterface != null) {
311 mStatusIntent = null;
312 agentDisconnect();
313 jniReset(mInterface);
314 mInterface = null;
315 mVpnUsers = null;
316 }
317
318 // Revoke the connection or stop LegacyVpnRunner.
319 if (mConnection != null) {
320 try {
321 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
322 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
323 } catch (Exception e) {
324 // ignore
325 }
326 mContext.unbindService(mConnection);
327 mConnection = null;
328 } else if (mLegacyVpnRunner != null) {
329 mLegacyVpnRunner.exit();
330 mLegacyVpnRunner = null;
331 }
332
333 try {
334 mNetd.denyProtect(mOwnerUID);
335 } catch (Exception e) {
336 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
337 }
338
339 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
340 mPackage = newPackage;
341 mOwnerUID = getAppUid(newPackage, mUserHandle);
342 try {
343 mNetd.allowProtect(mOwnerUID);
344 } catch (Exception e) {
345 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
346 }
347 mConfig = null;
348
349 updateState(DetailedState.IDLE, "prepare");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400350 } finally {
351 Binder.restoreCallingIdentity(token);
352 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700353 }
354
Jeff Davidson05542602014-08-11 14:07:27 -0700355 /**
Robin Lee3b3dd942015-05-12 18:14:58 +0100356 * Set whether a package has the ability to launch VPNs without user intervention.
Jeff Davidson05542602014-08-11 14:07:27 -0700357 */
Robin Lee244ce8e2016-01-05 18:03:46 +0000358 public boolean setPackageAuthorization(String packageName, boolean authorized) {
Jeff Davidson05542602014-08-11 14:07:27 -0700359 // Check if the caller is authorized.
Robin Lee244ce8e2016-01-05 18:03:46 +0000360 enforceControlPermissionOrInternalCaller();
Jeff Davidson05542602014-08-11 14:07:27 -0700361
Robin Lee3b3dd942015-05-12 18:14:58 +0100362 int uid = getAppUid(packageName, mUserHandle);
363 if (uid == -1 || VpnConfig.LEGACY_VPN.equals(packageName)) {
364 // Authorization for nonexistent packages (or fake ones) can't be updated.
Robin Lee244ce8e2016-01-05 18:03:46 +0000365 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700366 }
367
368 long token = Binder.clearCallingIdentity();
369 try {
370 AppOpsManager appOps =
371 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Robin Lee3b3dd942015-05-12 18:14:58 +0100372 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, uid, packageName,
Jeff Davidson05542602014-08-11 14:07:27 -0700373 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Robin Lee244ce8e2016-01-05 18:03:46 +0000374 return true;
Jeff Davidson05542602014-08-11 14:07:27 -0700375 } catch (Exception e) {
Robin Lee3b3dd942015-05-12 18:14:58 +0100376 Log.wtf(TAG, "Failed to set app ops for package " + packageName + ", uid " + uid, e);
Jeff Davidson05542602014-08-11 14:07:27 -0700377 } finally {
378 Binder.restoreCallingIdentity(token);
379 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000380 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700381 }
382
383 private boolean isVpnUserPreConsented(String packageName) {
384 AppOpsManager appOps =
385 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
386
387 // Verify that the caller matches the given package and has permission to activate VPNs.
388 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
389 packageName) == AppOpsManager.MODE_ALLOWED;
390 }
391
Paul Jensen0784eea2014-08-19 16:00:24 -0400392 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700393 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400394 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700395 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400396 PackageManager pm = mContext.getPackageManager();
397 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700398 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700399 result = pm.getPackageUidAsUser(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400400 } catch (NameNotFoundException e) {
401 result = -1;
402 }
403 return result;
404 }
405
406 public NetworkInfo getNetworkInfo() {
407 return mNetworkInfo;
408 }
409
Paul Jensen31a94f42015-02-13 14:18:39 -0500410 public int getNetId() {
411 return mNetworkAgent != null ? mNetworkAgent.netId : NETID_UNSET;
412 }
413
Lorenzo Colitti60446162014-09-20 00:14:31 +0900414 private LinkProperties makeLinkProperties() {
415 boolean allowIPv4 = mConfig.allowIPv4;
416 boolean allowIPv6 = mConfig.allowIPv6;
417
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400418 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900419
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400420 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700421
Lorenzo Colitti60446162014-09-20 00:14:31 +0900422 if (mConfig.addresses != null) {
423 for (LinkAddress address : mConfig.addresses) {
424 lp.addLinkAddress(address);
425 allowIPv4 |= address.getAddress() instanceof Inet4Address;
426 allowIPv6 |= address.getAddress() instanceof Inet6Address;
427 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400428 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900429
430 if (mConfig.routes != null) {
431 for (RouteInfo route : mConfig.routes) {
432 lp.addRoute(route);
433 InetAddress address = route.getDestination().getAddress();
434 allowIPv4 |= address instanceof Inet4Address;
435 allowIPv6 |= address instanceof Inet6Address;
436 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400437 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700438
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400439 if (mConfig.dnsServers != null) {
440 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700441 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
442 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900443 allowIPv4 |= address instanceof Inet4Address;
444 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400445 }
446 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700447
Lorenzo Colitti60446162014-09-20 00:14:31 +0900448 if (!allowIPv4) {
449 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
450 }
451 if (!allowIPv6) {
452 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
453 }
454
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400455 // Concatenate search domains into a string.
456 StringBuilder buffer = new StringBuilder();
457 if (mConfig.searchDomains != null) {
458 for (String domain : mConfig.searchDomains) {
459 buffer.append(domain).append(' ');
460 }
461 }
462 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700463
Lorenzo Colitti60446162014-09-20 00:14:31 +0900464 // TODO: Stop setting the MTU in jniCreate and set it here.
465
466 return lp;
467 }
468
469 private void agentConnect() {
470 LinkProperties lp = makeLinkProperties();
471
472 if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
473 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
474 } else {
475 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
476 }
477
Robin Lee323f29d2016-05-04 16:38:06 +0100478 mNetworkInfo.setDetailedState(DetailedState.CONNECTING, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700479
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700480 NetworkMisc networkMisc = new NetworkMisc();
Robin Lee17e61832016-05-09 13:46:28 +0100481 networkMisc.allowBypass = mConfig.allowBypass && !mLockdown;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700482
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400483 long token = Binder.clearCallingIdentity();
484 try {
485 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700486 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700487 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400488 public void unwanted() {
489 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700490 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400491 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700492 } finally {
493 Binder.restoreCallingIdentity(token);
494 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700495
Robin Lee4d03abc2016-05-09 12:32:27 +0100496 mVpnUsers = createUserAndRestrictedProfilesRanges(mUserHandle,
497 mConfig.allowedApplications, mConfig.disallowedApplications);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400498 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
Robin Lee323f29d2016-05-04 16:38:06 +0100499
500 mNetworkInfo.setIsAvailable(true);
501 updateState(DetailedState.CONNECTED, "agentConnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400502 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700503
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700504 private boolean canHaveRestrictedProfile(int userId) {
505 long token = Binder.clearCallingIdentity();
506 try {
507 return UserManager.get(mContext).canHaveRestrictedProfile(userId);
508 } finally {
509 Binder.restoreCallingIdentity(token);
510 }
511 }
512
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400513 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
514 networkInfo.setIsAvailable(false);
515 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
516 if (networkAgent != null) {
517 networkAgent.sendNetworkInfo(networkInfo);
518 }
519 }
520
521 private void agentDisconnect(NetworkAgent networkAgent) {
522 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
523 agentDisconnect(networkInfo, networkAgent);
524 }
525
526 private void agentDisconnect() {
527 if (mNetworkInfo.isConnected()) {
528 agentDisconnect(mNetworkInfo, mNetworkAgent);
529 mNetworkAgent = null;
530 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700531 }
532
533 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700534 * Establish a VPN network and return the file descriptor of the VPN
535 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700536 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700537 *
538 * @param config The parameters to configure the network.
539 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700540 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700541 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700542 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700543 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400544 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700545 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700546 }
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700547 // Check to ensure consent hasn't been revoked since we were prepared.
548 if (!isVpnUserPreConsented(mPackage)) {
549 return null;
550 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700551 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700552 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
553 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700554 long token = Binder.clearCallingIdentity();
555 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700556 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400557 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +0000558 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
559 new UserHandle(mUserHandle))) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700560 throw new SecurityException("Restricted users cannot establish VPNs");
561 }
562
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700563 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400564 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700565 if (info == null) {
566 throw new SecurityException("Cannot find " + config.user);
567 }
568 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
569 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
570 }
571 } catch (RemoteException e) {
572 throw new SecurityException("Cannot find " + config.user);
573 } finally {
574 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700575 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700576
Chad Brubaker850eb672014-03-21 21:02:47 +0000577 // Save the old config in case we need to go back.
578 VpnConfig oldConfig = mConfig;
579 String oldInterface = mInterface;
580 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400581 NetworkAgent oldNetworkAgent = mNetworkAgent;
582 mNetworkAgent = null;
Robin Lee4d03abc2016-05-09 12:32:27 +0100583 Set<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000584
Chia-chi Yehe9107902011-07-02 01:48:50 -0700585 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700586 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700587 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700588 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700589 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700590
Chad Brubakerc2865192013-07-10 14:46:23 -0700591 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700592 StringBuilder builder = new StringBuilder();
593 for (LinkAddress address : config.addresses) {
594 builder.append(" " + address);
595 }
596 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700597 throw new IllegalArgumentException("At least one address must be specified");
598 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700599 Connection connection = new Connection();
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700600 if (!mContext.bindServiceAsUser(intent, connection,
601 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
602 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700603 throw new IllegalStateException("Cannot bind " + config.user);
604 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000605
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700606 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700607 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700608
609 // Fill more values.
610 config.user = mPackage;
611 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700612 config.startTime = SystemClock.elapsedRealtime();
613 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000614
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700615 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400616 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000617
618 if (oldConnection != null) {
619 mContext.unbindService(oldConnection);
620 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400621 // Remove the old tun's user forwarding rules
622 // The new tun's user rules have already been added so they will take over
623 // as rules are deleted. This prevents data leakage as the rules are moved over.
624 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000625 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000626 jniReset(oldInterface);
627 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700628
629 try {
630 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
631 } catch (IOException e) {
632 throw new IllegalStateException(
633 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
634 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000635 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000636 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400637 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000638 // restore old state
639 mConfig = oldConfig;
640 mConnection = oldConnection;
641 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400642 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000643 mInterface = oldInterface;
644 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700645 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000646 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700647 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700648 }
649
Chad Brubakerc2865192013-07-10 14:46:23 -0700650 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800651 return mNetworkAgent != null && mInterface != null;
652 }
653
654 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
655 // that a call to mutate VPN state is admissible.
656 private boolean isCallerEstablishedOwnerLocked() {
657 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -0700658 }
659
Paul Jensen0784eea2014-08-19 16:00:24 -0400660 // Note: Return type guarantees results are deduped and sorted, which callers require.
661 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
662 SortedSet<Integer> uids = new TreeSet<Integer>();
663 for (String app : packageNames) {
664 int uid = getAppUid(app, userHandle);
665 if (uid != -1) uids.add(uid);
666 }
667 return uids;
668 }
669
Robin Lee4d03abc2016-05-09 12:32:27 +0100670 /**
671 * Creates a {@link Set} of non-intersecting {@link UidRange} objects including all UIDs
672 * associated with one user, and any restricted profiles attached to that user.
673 *
674 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
675 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
676 * in each user and profile will be included.
677 *
678 * @param userHandle The userId to create UID ranges for along with any of its restricted
679 * profiles.
680 * @param allowedApplications (optional) whitelist of applications to include.
681 * @param disallowedApplications (optional) blacklist of applications to exclude.
682 */
683 @VisibleForTesting
684 Set<UidRange> createUserAndRestrictedProfilesRanges(@UserIdInt int userHandle,
685 @Nullable List<String> allowedApplications,
686 @Nullable List<String> disallowedApplications) {
687 final Set<UidRange> ranges = new ArraySet<>();
Robert Greenwalt69887e82013-09-24 11:05:57 -0700688
Robin Lee4d03abc2016-05-09 12:32:27 +0100689 // Assign the top-level user to the set of ranges
690 addUserToRanges(ranges, userHandle, allowedApplications, disallowedApplications);
691
692 // If the user can have restricted profiles, assign all its restricted profiles too
693 if (canHaveRestrictedProfile(userHandle)) {
694 final long token = Binder.clearCallingIdentity();
695 List<UserInfo> users;
696 try {
Robin Lee17e61832016-05-09 13:46:28 +0100697 users = UserManager.get(mContext).getUsers(true);
Robin Lee4d03abc2016-05-09 12:32:27 +0100698 } finally {
699 Binder.restoreCallingIdentity(token);
700 }
701 for (UserInfo user : users) {
702 if (user.isRestricted() && (user.restrictedProfileParentId == userHandle)) {
703 addUserToRanges(ranges, user.id, allowedApplications, disallowedApplications);
704 }
705 }
706 }
707 return ranges;
708 }
709
710 /**
711 * Updates a {@link Set} of non-intersecting {@link UidRange} objects to include all UIDs
712 * associated with one user.
713 *
714 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
715 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
716 * in the user will be included.
717 *
718 * @param ranges {@link Set} of {@link UidRange}s to which to add.
719 * @param userHandle The userId to add to {@param ranges}.
720 * @param allowedApplications (optional) whitelist of applications to include.
721 * @param disallowedApplications (optional) blacklist of applications to exclude.
722 */
723 @VisibleForTesting
724 void addUserToRanges(@NonNull Set<UidRange> ranges, @UserIdInt int userHandle,
725 @Nullable List<String> allowedApplications,
726 @Nullable List<String> disallowedApplications) {
727 if (allowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400728 // Add ranges covering all UIDs for allowedApplications.
729 int start = -1, stop = -1;
Robin Lee4d03abc2016-05-09 12:32:27 +0100730 for (int uid : getAppsUids(allowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400731 if (start == -1) {
732 start = uid;
733 } else if (uid != stop + 1) {
Robin Lee4d03abc2016-05-09 12:32:27 +0100734 ranges.add(new UidRange(start, stop));
Paul Jensen0784eea2014-08-19 16:00:24 -0400735 start = uid;
736 }
737 stop = uid;
738 }
Robin Lee4d03abc2016-05-09 12:32:27 +0100739 if (start != -1) ranges.add(new UidRange(start, stop));
740 } else if (disallowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400741 // Add all ranges for user skipping UIDs for disallowedApplications.
742 final UidRange userRange = UidRange.createForUser(userHandle);
743 int start = userRange.start;
Robin Lee4d03abc2016-05-09 12:32:27 +0100744 for (int uid : getAppsUids(disallowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400745 if (uid == start) {
746 start++;
747 } else {
Robin Lee4d03abc2016-05-09 12:32:27 +0100748 ranges.add(new UidRange(start, uid - 1));
Paul Jensen0784eea2014-08-19 16:00:24 -0400749 start = uid + 1;
750 }
751 }
Robin Lee4d03abc2016-05-09 12:32:27 +0100752 if (start <= userRange.stop) ranges.add(new UidRange(start, userRange.stop));
Paul Jensen0784eea2014-08-19 16:00:24 -0400753 } else {
754 // Add all UIDs for the user.
Robin Lee4d03abc2016-05-09 12:32:27 +0100755 ranges.add(UidRange.createForUser(userHandle));
Paul Jensen0784eea2014-08-19 16:00:24 -0400756 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700757 }
758
Paul Jensen0784eea2014-08-19 16:00:24 -0400759 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
760 // apply to userHandle.
761 private List<UidRange> uidRangesForUser(int userHandle) {
762 final UidRange userRange = UidRange.createForUser(userHandle);
763 final List<UidRange> ranges = new ArrayList<UidRange>();
764 for (UidRange range : mVpnUsers) {
Robin Lee4d03abc2016-05-09 12:32:27 +0100765 if (userRange.containsRange(range)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400766 ranges.add(range);
767 }
768 }
769 return ranges;
770 }
771
772 private void removeVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800773 if (mVpnUsers == null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700774 throw new IllegalStateException("VPN is not active");
775 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400776 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700777 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400778 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700779 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400780 mVpnUsers.removeAll(ranges);
Chad Brubakerc2865192013-07-10 14:46:23 -0700781 }
782
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700783 public void onUserAdded(int userHandle) {
784 // If the user is restricted tie them to the parent user's VPN
785 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +0100786 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700787 synchronized(Vpn.this) {
Robin Lee17e61832016-05-09 13:46:28 +0100788 if (mVpnUsers != null) {
789 try {
790 addUserToRanges(mVpnUsers, userHandle, mConfig.allowedApplications,
791 mConfig.disallowedApplications);
792 if (mNetworkAgent != null) {
793 final List<UidRange> ranges = uidRangesForUser(userHandle);
794 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
795 }
796 } catch (Exception e) {
797 Log.wtf(TAG, "Failed to add restricted user to owner", e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400798 }
Robin Lee17e61832016-05-09 13:46:28 +0100799 }
800 if (mAlwaysOn) {
801 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -0700802 }
803 }
804 }
805 }
806
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700807 public void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700808 // clean up if restricted
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700809 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +0100810 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700811 synchronized(Vpn.this) {
Robin Lee17e61832016-05-09 13:46:28 +0100812 if (mVpnUsers != null) {
813 try {
814 removeVpnUserLocked(userHandle);
815 } catch (Exception e) {
816 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
817 }
818 }
819 if (mAlwaysOn) {
820 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -0700821 }
822 }
823 }
824 }
825
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700826 /**
Robin Lee17e61832016-05-09 13:46:28 +0100827 * Called when the user associated with this VPN has just been stopped.
828 */
829 public synchronized void onUserStopped() {
830 // Switch off networking lockdown (if it was enabled)
831 setVpnForcedLocked(false);
832 mAlwaysOn = false;
833
834 // Quit any active connections
835 agentDisconnect();
836 }
837
838 /**
839 * Restrict network access from all UIDs affected by this {@link Vpn}, apart from the VPN
840 * service app itself, to only sockets that have had {@code protect()} called on them. All
841 * non-VPN traffic is blocked via a {@code PROHIBIT} response from the kernel.
842 *
843 * The exception for the VPN UID isn't technically necessary -- setup should use protected
844 * sockets -- but in practice it saves apps that don't protect their sockets from breaking.
845 *
846 * Calling multiple times with {@param enforce} = {@code true} will recreate the set of UIDs to
847 * block every time, and if anything has changed update using {@link #setAllowOnlyVpnForUids}.
848 *
849 * @param enforce {@code true} to require that all traffic under the jurisdiction of this
850 * {@link Vpn} goes through a VPN connection or is blocked until one is
851 * available, {@code false} to lift the requirement.
852 *
853 * @see #mBlockedUsers
854 */
855 @GuardedBy("this")
856 private void setVpnForcedLocked(boolean enforce) {
857 final Set<UidRange> removedRanges = new ArraySet<>(mBlockedUsers);
858 if (enforce) {
859 final Set<UidRange> addedRanges = createUserAndRestrictedProfilesRanges(mUserHandle,
860 /* allowedApplications */ null,
861 /* disallowedApplications */ Collections.singletonList(mPackage));
862
863 removedRanges.removeAll(addedRanges);
864 addedRanges.removeAll(mBlockedUsers);
865
866 setAllowOnlyVpnForUids(false, removedRanges);
867 setAllowOnlyVpnForUids(true, addedRanges);
868 } else {
869 setAllowOnlyVpnForUids(false, removedRanges);
870 }
871 }
872
873 /**
874 * Either add or remove a list of {@link UidRange}s to the list of UIDs that are only allowed
875 * to make connections through sockets that have had {@code protect()} called on them.
876 *
877 * @param enforce {@code true} to add to the blacklist, {@code false} to remove.
878 * @param ranges {@link Collection} of {@link UidRange}s to add (if {@param enforce} is
879 * {@code true}) or to remove.
880 * @return {@code true} if all of the UIDs were added/removed. {@code false} otherwise,
881 * including added ranges that already existed or removed ones that didn't.
882 */
883 @GuardedBy("this")
884 private boolean setAllowOnlyVpnForUids(boolean enforce, Collection<UidRange> ranges) {
885 if (ranges.size() == 0) {
886 return true;
887 }
888 final UidRange[] rangesArray = ranges.toArray(new UidRange[ranges.size()]);
889 try {
890 mNetd.setAllowOnlyVpnForUids(enforce, rangesArray);
891 } catch (RemoteException | RuntimeException e) {
892 Log.e(TAG, "Updating blocked=" + enforce
893 + " for UIDs " + Arrays.toString(ranges.toArray()) + " failed", e);
894 return false;
895 }
896 if (enforce) {
897 mBlockedUsers.addAll(ranges);
898 } else {
899 mBlockedUsers.removeAll(ranges);
900 }
901 return true;
902 }
903
904 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700905 * Return the configuration of the currently running VPN.
906 */
907 public VpnConfig getVpnConfig() {
908 enforceControlPermission();
909 return mConfig;
910 }
911
Jeff Sharkey899223b2012-08-04 15:24:58 -0700912 @Deprecated
913 public synchronized void interfaceStatusChanged(String iface, boolean up) {
914 try {
915 mObserver.interfaceStatusChanged(iface, up);
916 } catch (RemoteException e) {
917 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700918 }
919 }
920
Jeff Sharkey899223b2012-08-04 15:24:58 -0700921 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
922 @Override
923 public void interfaceStatusChanged(String interfaze, boolean up) {
924 synchronized (Vpn.this) {
925 if (!up && mLegacyVpnRunner != null) {
926 mLegacyVpnRunner.check(interfaze);
927 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700928 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700929 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700930
Jeff Sharkey899223b2012-08-04 15:24:58 -0700931 @Override
932 public void interfaceRemoved(String interfaze) {
933 synchronized (Vpn.this) {
934 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700935 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400936 mVpnUsers = null;
Paul Jensenc4c72312014-12-08 14:04:51 -0500937 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700938 mInterface = null;
939 if (mConnection != null) {
940 mContext.unbindService(mConnection);
941 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400942 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700943 } else if (mLegacyVpnRunner != null) {
944 mLegacyVpnRunner.exit();
945 mLegacyVpnRunner = null;
946 }
947 }
948 }
949 }
950 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700951
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700952 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -0800953 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700954 }
955
Robin Lee244ce8e2016-01-05 18:03:46 +0000956 private void enforceControlPermissionOrInternalCaller() {
957 // Require caller to be either an application with CONTROL_VPN permission or a process
958 // in the system server.
959 mContext.enforceCallingOrSelfPermission(Manifest.permission.CONTROL_VPN,
960 "Unauthorized Caller");
961 }
962
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700963 private class Connection implements ServiceConnection {
964 private IBinder mService;
965
966 @Override
967 public void onServiceConnected(ComponentName name, IBinder service) {
968 mService = service;
969 }
970
971 @Override
972 public void onServiceDisconnected(ComponentName name) {
973 mService = null;
974 }
975 }
976
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700977 private void prepareStatusIntent() {
978 final long token = Binder.clearCallingIdentity();
979 try {
980 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
981 } finally {
982 Binder.restoreCallingIdentity(token);
983 }
984 }
985
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700986 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800987 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700988 return false;
989 }
990 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800991 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700992 return success;
993 }
994
995 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800996 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700997 return false;
998 }
999 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001000 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001001 return success;
1002 }
1003
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001004 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
1005 if (!isCallerEstablishedOwnerLocked()) {
1006 return false;
1007 }
1008 if (networks == null) {
1009 mConfig.underlyingNetworks = null;
1010 } else {
1011 mConfig.underlyingNetworks = new Network[networks.length];
1012 for (int i = 0; i < networks.length; ++i) {
1013 if (networks[i] == null) {
1014 mConfig.underlyingNetworks[i] = null;
1015 } else {
1016 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
1017 }
1018 }
1019 }
1020 return true;
1021 }
1022
1023 public synchronized Network[] getUnderlyingNetworks() {
1024 if (!isRunningLocked()) {
1025 return null;
1026 }
1027 return mConfig.underlyingNetworks;
1028 }
1029
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001030 /**
1031 * This method should only be called by ConnectivityService. Because it doesn't
1032 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
1033 */
1034 public synchronized VpnInfo getVpnInfo() {
1035 if (!isRunningLocked()) {
1036 return null;
1037 }
1038
1039 VpnInfo info = new VpnInfo();
1040 info.ownerUid = mOwnerUID;
1041 info.vpnIface = mInterface;
1042 return info;
1043 }
1044
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001045 public synchronized boolean appliesToUid(int uid) {
1046 if (!isRunningLocked()) {
1047 return false;
1048 }
1049 for (UidRange uidRange : mVpnUsers) {
Robin Lee4d03abc2016-05-09 12:32:27 +01001050 if (uidRange.contains(uid)) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001051 return true;
1052 }
1053 }
1054 return false;
1055 }
1056
Robin Lee17e61832016-05-09 13:46:28 +01001057 /**
1058 * @return {@code true} if the set of users blocked whilst waiting for VPN to connect includes
1059 * the UID {@param uid}, {@code false} otherwise.
1060 *
1061 * @see #mBlockedUsers
1062 */
1063 public synchronized boolean isBlockingUid(int uid) {
1064 for (UidRange uidRange : mBlockedUsers) {
1065 if (uidRange.contains(uid)) {
1066 return true;
1067 }
1068 }
1069 return false;
1070 }
1071
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001072 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001073 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001074 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001075 private native void jniReset(String interfaze);
1076 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001077 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
1078 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001079
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001080 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
1081 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -07001082 // Currently legacy VPN only works on IPv4.
1083 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001084 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001085 }
1086 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001087
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001088 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -07001089 }
1090
1091 /**
1092 * Start legacy VPN, controlling native daemons as needed. Creates a
1093 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001094 *
1095 * Should only be called to respond to Binder requests as this enforces caller permission. Use
1096 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
1097 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -07001098 */
1099 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001100 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001101 long token = Binder.clearCallingIdentity();
1102 try {
1103 startLegacyVpnPrivileged(profile, keyStore, egress);
1104 } finally {
1105 Binder.restoreCallingIdentity(token);
1106 }
1107 }
1108
1109 /**
1110 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
1111 * permissions under the assumption that the caller is the system.
1112 *
1113 * Callers are responsible for checking permissions if needed.
1114 */
1115 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
1116 LinkProperties egress) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001117 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -04001118 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +00001119 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
1120 new UserHandle(mUserHandle))) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001121 throw new SecurityException("Restricted users cannot establish VPNs");
1122 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001123
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001124 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
1125 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
1126 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -07001127
1128 // Load certificates.
1129 String privateKey = "";
1130 String userCert = "";
1131 String caCert = "";
1132 String serverCert = "";
1133 if (!profile.ipsecUserCert.isEmpty()) {
1134 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
1135 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001136 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001137 }
1138 if (!profile.ipsecCaCert.isEmpty()) {
1139 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001140 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001141 }
1142 if (!profile.ipsecServerCert.isEmpty()) {
1143 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001144 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001145 }
1146 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
1147 throw new IllegalStateException("Cannot load credentials");
1148 }
1149
1150 // Prepare arguments for racoon.
1151 String[] racoon = null;
1152 switch (profile.type) {
1153 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1154 racoon = new String[] {
1155 iface, profile.server, "udppsk", profile.ipsecIdentifier,
1156 profile.ipsecSecret, "1701",
1157 };
1158 break;
1159 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1160 racoon = new String[] {
1161 iface, profile.server, "udprsa", privateKey, userCert,
1162 caCert, serverCert, "1701",
1163 };
1164 break;
1165 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
1166 racoon = new String[] {
1167 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
1168 profile.ipsecSecret, profile.username, profile.password, "", gateway,
1169 };
1170 break;
1171 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
1172 racoon = new String[] {
1173 iface, profile.server, "xauthrsa", privateKey, userCert,
1174 caCert, serverCert, profile.username, profile.password, "", gateway,
1175 };
1176 break;
1177 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
1178 racoon = new String[] {
1179 iface, profile.server, "hybridrsa",
1180 caCert, serverCert, profile.username, profile.password, "", gateway,
1181 };
1182 break;
1183 }
1184
1185 // Prepare arguments for mtpd.
1186 String[] mtpd = null;
1187 switch (profile.type) {
1188 case VpnProfile.TYPE_PPTP:
1189 mtpd = new String[] {
1190 iface, "pptp", profile.server, "1723",
1191 "name", profile.username, "password", profile.password,
1192 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1193 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1194 (profile.mppe ? "+mppe" : "nomppe"),
1195 };
1196 break;
1197 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1198 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1199 mtpd = new String[] {
1200 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
1201 "name", profile.username, "password", profile.password,
1202 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1203 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1204 };
1205 break;
1206 }
1207
1208 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001209 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001210 config.user = profile.key;
1211 config.interfaze = iface;
1212 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001213
1214 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001215 if (!profile.dnsServers.isEmpty()) {
1216 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
1217 }
1218 if (!profile.searchDomains.isEmpty()) {
1219 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1220 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001221 startLegacyVpn(config, racoon, mtpd);
1222 }
1223
1224 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001225 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001226
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001227 // Prepare for the new request.
1228 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -07001229 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001230
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001231 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001232 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1233 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001234 }
1235
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001236 /** Stop legacy VPN. Permissions must be checked by callers. */
1237 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001238 if (mLegacyVpnRunner != null) {
1239 mLegacyVpnRunner.exit();
1240 mLegacyVpnRunner = null;
1241
1242 synchronized (LegacyVpnRunner.TAG) {
1243 // wait for old thread to completely finish before spinning up
1244 // new instance, otherwise state updates can be out of order.
1245 }
1246 }
1247 }
1248
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001249 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001250 * Return the information of the current ongoing legacy VPN.
1251 */
1252 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001253 // Check if the caller is authorized.
1254 enforceControlPermission();
sj.cha08bbca02015-03-23 11:35:24 +09001255 return getLegacyVpnInfoPrivileged();
1256 }
1257
1258 /**
1259 * Return the information of the current ongoing legacy VPN.
1260 * Callers are responsible for checking permissions if needed.
1261 */
1262 public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001263 if (mLegacyVpnRunner == null) return null;
1264
1265 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001266 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001267 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001268 if (mNetworkInfo.isConnected()) {
1269 info.intent = mStatusIntent;
1270 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001271 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001272 }
1273
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001274 public VpnConfig getLegacyVpnConfig() {
1275 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001276 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001277 } else {
1278 return null;
1279 }
1280 }
1281
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001282 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001283 * Bringing up a VPN connection takes time, and that is all this thread
1284 * does. Here we have plenty of time. The only thing we need to take
1285 * care of is responding to interruptions as soon as possible. Otherwise
1286 * requests will be piled up. This can be done in a Handler as a state
1287 * machine, but it is much easier to read in the current form.
1288 */
1289 private class LegacyVpnRunner extends Thread {
1290 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001291
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001292 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001293 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001294 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001295 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001296 private final AtomicInteger mOuterConnection =
1297 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001298
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001299 private long mTimer = -1;
1300
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001301 /**
1302 * Watch for the outer connection (passing in the constructor) going away.
1303 */
1304 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1305 @Override
1306 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001307 if (!mEnableTeardown) return;
1308
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001309 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1310 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1311 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1312 NetworkInfo info = (NetworkInfo)intent.getExtra(
1313 ConnectivityManager.EXTRA_NETWORK_INFO);
1314 if (info != null && !info.isConnectedOrConnecting()) {
1315 try {
1316 mObserver.interfaceStatusChanged(mOuterInterface, false);
1317 } catch (RemoteException e) {}
1318 }
1319 }
1320 }
1321 }
1322 };
1323
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001324 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001325 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001326 mConfig = config;
1327 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001328 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001329 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001330 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001331
1332 // This is the interface which VPN is running on,
1333 // mConfig.interfaze will change to point to OUR
1334 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001335 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001336 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001337 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001338 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001339
Paul Jensene75b9e32015-04-06 11:54:53 -04001340 if (!TextUtils.isEmpty(mOuterInterface)) {
1341 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1342 for (Network network : cm.getAllNetworks()) {
1343 final LinkProperties lp = cm.getLinkProperties(network);
Lorenzo Colitti1b60d112015-07-02 13:03:03 +09001344 if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001345 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1346 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1347 }
1348 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001349 }
1350
1351 IntentFilter filter = new IntentFilter();
1352 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1353 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001354 }
1355
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001356 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001357 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001358 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1359 exit();
1360 }
1361 }
1362
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001363 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001364 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001365 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001366 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001367 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001368 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001369 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001370 try {
1371 mContext.unregisterReceiver(mBroadcastReceiver);
1372 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001373 }
1374
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001375 @Override
1376 public void run() {
1377 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001378 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001379 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001380 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001381 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001382 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001383 }
1384 }
1385
1386 private void checkpoint(boolean yield) throws InterruptedException {
1387 long now = SystemClock.elapsedRealtime();
1388 if (mTimer == -1) {
1389 mTimer = now;
1390 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001391 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001392 Thread.sleep(yield ? 200 : 1);
1393 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001394 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001395 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001396 }
1397 }
1398
1399 private void execute() {
1400 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001401 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001402 try {
1403 // Initialize the timer.
1404 checkpoint(false);
1405
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001406 // Wait for the daemons to stop.
1407 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001408 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001409 checkpoint(true);
1410 }
1411 }
1412
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001413 // Clear the previous state.
1414 File state = new File("/data/misc/vpn/state");
1415 state.delete();
1416 if (state.exists()) {
1417 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001418 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001419 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001420 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001421
Chia-chi Yehe9107902011-07-02 01:48:50 -07001422 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001423 boolean restart = false;
1424 for (String[] arguments : mArguments) {
1425 restart = restart || (arguments != null);
1426 }
1427 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001428 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001429 return;
1430 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001431 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001432
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001433 // Start the daemon with arguments.
1434 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001435 String[] arguments = mArguments[i];
1436 if (arguments == null) {
1437 continue;
1438 }
1439
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001440 // Start the daemon.
1441 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001442 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001443
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001444 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001445 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001446 checkpoint(true);
1447 }
1448
1449 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001450 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001451 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001452 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001453
1454 // Wait for the socket to connect.
1455 while (true) {
1456 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001457 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001458 break;
1459 } catch (Exception e) {
1460 // ignore
1461 }
1462 checkpoint(true);
1463 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001464 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001465
1466 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001467 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001468 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001469 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001470 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001471 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001472 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001473 out.write(bytes.length >> 8);
1474 out.write(bytes.length);
1475 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001476 checkpoint(false);
1477 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001478 out.write(0xFF);
1479 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001480 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001481
1482 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001483 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001484 while (true) {
1485 try {
1486 if (in.read() == -1) {
1487 break;
1488 }
1489 } catch (Exception e) {
1490 // ignore
1491 }
1492 checkpoint(true);
1493 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001494 }
1495
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001496 // Wait for the daemons to create the new state.
1497 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001498 // Check if a running daemon is dead.
1499 for (int i = 0; i < mDaemons.length; ++i) {
1500 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001501 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001502 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001503 }
1504 }
1505 checkpoint(true);
1506 }
1507
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001508 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001509 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001510 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001511 throw new IllegalStateException("Cannot parse the state");
1512 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001513
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001514 // Set the interface and the addresses in the config.
1515 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001516
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001517 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001518 // Set the routes if they are not set in the config.
1519 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001520 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001521 }
1522
1523 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001524 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001525 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001526 if (!dnsServers.isEmpty()) {
1527 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1528 }
1529 }
1530
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001531 // Set the search domains if they are not set in the config.
1532 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1533 String searchDomains = parameters[4].trim();
1534 if (!searchDomains.isEmpty()) {
1535 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1536 }
1537 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001538
Lorenzo Colitti50262792014-09-19 01:53:35 +09001539 // Add a throw route for the VPN server endpoint, if one was specified.
1540 String endpoint = parameters[5];
1541 if (!endpoint.isEmpty()) {
1542 try {
1543 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1544 if (addr instanceof Inet4Address) {
1545 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1546 } else if (addr instanceof Inet6Address) {
1547 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1548 } else {
1549 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1550 }
1551 } catch (IllegalArgumentException e) {
1552 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1553 }
1554 }
1555
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001556 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001557 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001558 // Set the start time
1559 mConfig.startTime = SystemClock.elapsedRealtime();
1560
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001561 // Check if the thread is interrupted while we are waiting.
1562 checkpoint(false);
1563
Chia-chi Yehe9107902011-07-02 01:48:50 -07001564 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001565 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001566 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001567 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001568
1569 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001570 mInterface = mConfig.interfaze;
Robin Lee4d03abc2016-05-09 12:32:27 +01001571 prepareStatusIntent();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001572
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001573 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001574
1575 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001576 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001577 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001578 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001579 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001580 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001581 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001582 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001583 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001584 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001585 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001586 }
1587 }
1588
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001589 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001590 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001591 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001592 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001593 }
1594 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001595
1596 /**
1597 * Monitor the daemons we started, moving to disconnected state if the
1598 * underlying services fail.
1599 */
1600 private void monitorDaemons() {
1601 if (!mNetworkInfo.isConnected()) {
1602 return;
1603 }
1604
1605 try {
1606 while (true) {
1607 Thread.sleep(2000);
1608 for (int i = 0; i < mDaemons.length; i++) {
1609 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1610 return;
1611 }
1612 }
1613 }
1614 } catch (InterruptedException e) {
1615 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1616 } finally {
1617 for (String daemon : mDaemons) {
1618 SystemService.stop(daemon);
1619 }
1620
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001621 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001622 }
1623 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001624 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001625}