blob: 4b5a2cb0eb1a70f3940bb8928acefa71c71fb3dd [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;
20
Chad Brubaker4ca19e82013-06-14 11:16:51 -070021import android.app.AppGlobals;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070022import android.app.Notification;
23import android.app.NotificationManager;
Jeff Sharkey899223b2012-08-04 15:24:58 -070024import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070025import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070026import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070027import android.content.Context;
28import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070029import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070030import android.content.ServiceConnection;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070031import android.content.pm.ApplicationInfo;
32import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040033import android.content.pm.PackageManager.NameNotFoundException;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070034import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070035import android.content.pm.UserInfo;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070036import android.graphics.Bitmap;
37import android.graphics.Canvas;
38import android.graphics.drawable.Drawable;
Jeff Sharkey899223b2012-08-04 15:24:58 -070039import android.net.BaseNetworkStateTracker;
40import android.net.ConnectivityManager;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070041import android.net.IConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070042import android.net.INetworkManagementEventObserver;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070043import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070044import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070045import android.net.LocalSocket;
46import android.net.LocalSocketAddress;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040047import android.net.NetworkAgent;
48import android.net.NetworkCapabilities;
Jeff Sharkey899223b2012-08-04 15:24:58 -070049import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040050import android.net.NetworkInfo.DetailedState;
Chad Brubakerc0234532014-02-14 13:24:29 -080051import android.net.NetworkUtils;
Jeff Sharkey82f85212012-08-24 11:17:25 -070052import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040053import android.net.UidRange;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070054import android.os.Binder;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080055import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070056import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070057import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040058import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070059import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070060import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070061import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070062import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070063import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070064import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070065import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070066import android.os.UserManager;
Jeff Sharkey82f85212012-08-24 11:17:25 -070067import android.security.Credentials;
68import android.security.KeyStore;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070069import android.util.Log;
Chad Brubakerc2865192013-07-10 14:46:23 -070070import android.util.SparseBooleanArray;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070071
Chad Brubakerc2865192013-07-10 14:46:23 -070072import com.android.internal.annotations.GuardedBy;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070073import com.android.internal.R;
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
Chia-chi Yeh97a61562011-07-14 15:05:05 -070079import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070080import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070081import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070082import java.io.OutputStream;
Chad Brubakerc0234532014-02-14 13:24:29 -080083import java.net.InetAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070084import java.net.Inet4Address;
Elliott Hughesd396a442013-06-28 16:24:48 -070085import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040086import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070087import java.util.Arrays;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040088import java.util.List;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070089import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070090
Jeff Sharkey065b2992012-08-05 14:16:48 -070091import libcore.io.IoUtils;
92
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070093/**
94 * @hide
95 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040096public class Vpn {
97 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -070098 private static final String TAG = "Vpn";
99 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400100
Jeff Sharkey899223b2012-08-04 15:24:58 -0700101 // TODO: create separate trackers for each unique VPN to support
102 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700103
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400104 private Context mContext;
105 private NetworkInfo mNetworkInfo;
106 private String mPackage;
107 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700108 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700109 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700110 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700111 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700112 private volatile boolean mEnableNotif = true;
113 private volatile boolean mEnableTeardown = true;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700114 private final IConnectivityManager mConnService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400115 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700116 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400117 private NetworkAgent mNetworkAgent;
118 private final Looper mLooper;
119 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700120
121 /* list of users using this VPN. */
122 @GuardedBy("this")
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400123 private List<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700124 private BroadcastReceiver mUserIntentReceiver = null;
125
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700126 private final int mUserId;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700127
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400128 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700129 IConnectivityManager connService, int userId) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700130 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400131 mNetd = netService;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700132 mConnService = connService;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700133 mUserId = userId;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400134 mLooper = looper;
135
136 mPackage = VpnConfig.LEGACY_VPN;
137 mOwnerUID = getAppUid(mPackage);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700138
139 try {
140 netService.registerObserver(mObserver);
141 } catch (RemoteException e) {
142 Log.wtf(TAG, "Problem registering observer", e);
143 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700144 if (userId == UserHandle.USER_OWNER) {
145 // Owner's VPN also needs to handle restricted users
146 mUserIntentReceiver = new BroadcastReceiver() {
147 @Override
148 public void onReceive(Context context, Intent intent) {
149 final String action = intent.getAction();
150 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
151 UserHandle.USER_NULL);
152 if (userId == UserHandle.USER_NULL) return;
153
154 if (Intent.ACTION_USER_ADDED.equals(action)) {
155 onUserAdded(userId);
156 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
157 onUserRemoved(userId);
158 }
159 }
160 };
161
162 IntentFilter intentFilter = new IntentFilter();
163 intentFilter.addAction(Intent.ACTION_USER_ADDED);
164 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
165 mContext.registerReceiverAsUser(
166 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
167 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400168
169 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
170 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
171 mNetworkCapabilities = new NetworkCapabilities();
172 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
173 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700174 }
175
Jeff Sharkey57666932013-04-30 17:01:57 -0700176 /**
177 * Set if this object is responsible for showing its own notifications. When
178 * {@code false}, notifications are handled externally by someone else.
179 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700180 public void setEnableNotifications(boolean enableNotif) {
181 mEnableNotif = enableNotif;
182 }
183
Jeff Sharkey57666932013-04-30 17:01:57 -0700184 /**
185 * Set if this object is responsible for watching for {@link NetworkInfo}
186 * teardown. When {@code false}, teardown is handled externally by someone
187 * else.
188 */
189 public void setEnableTeardown(boolean enableTeardown) {
190 mEnableTeardown = enableTeardown;
191 }
192
Jeff Sharkey899223b2012-08-04 15:24:58 -0700193 /**
194 * Update current state, dispaching event to listeners.
195 */
196 private void updateState(DetailedState detailedState, String reason) {
197 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
198 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400199 if (mNetworkAgent != null) {
200 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
201 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700202 }
203
204 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700205 * Prepare for a VPN application. This method is designed to solve
206 * race conditions. It first compares the current prepared package
207 * with {@code oldPackage}. If they are the same, the prepared
208 * package is revoked and replaced with {@code newPackage}. If
209 * {@code oldPackage} is {@code null}, the comparison is omitted.
210 * If {@code newPackage} is the same package or {@code null}, the
211 * revocation is omitted. This method returns {@code true} if the
212 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700213 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700214 * Legacy VPN is handled specially since it is not a real package.
215 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
216 * it can be revoked by itself.
217 *
218 * @param oldPackage The package name of the old VPN application.
219 * @param newPackage The package name of the new VPN application.
220 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700221 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700222 public synchronized boolean prepare(String oldPackage, String newPackage) {
223 // Return false if the package does not match.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700224 if (oldPackage != null && !oldPackage.equals(mPackage)) {
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.
229 if (newPackage == null ||
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700230 (newPackage.equals(mPackage) && !newPackage.equals(VpnConfig.LEGACY_VPN))) {
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
Chia-chi Yehe9107902011-07-02 01:48:50 -0700237 // Reset the interface and hide the notification.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700238 if (mInterface != null) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400239 for (UidRange uidRange : mVpnUsers) {
240 hideNotification(uidRange.getStartUser());
Jeff Sharkey899223b2012-08-04 15:24:58 -0700241 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400242 agentDisconnect();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700243 jniReset(mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700244 mInterface = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700245 mVpnUsers = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700246 }
247
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700248 // Revoke the connection or stop LegacyVpnRunner.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700249 if (mConnection != null) {
250 try {
251 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
252 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
253 } catch (Exception e) {
254 // ignore
255 }
256 mContext.unbindService(mConnection);
257 mConnection = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700258 } else if (mLegacyVpnRunner != null) {
259 mLegacyVpnRunner.exit();
260 mLegacyVpnRunner = null;
261 }
262
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400263 long token = Binder.clearCallingIdentity();
264 try {
265 mNetd.denyProtect(mOwnerUID);
266 } catch (Exception e) {
267 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
268 } finally {
269 Binder.restoreCallingIdentity(token);
270 }
271
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700272 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
273 mPackage = newPackage;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400274 mOwnerUID = getAppUid(newPackage);
275 token = Binder.clearCallingIdentity();
276 try {
277 mNetd.allowProtect(mOwnerUID);
278 } catch (Exception e) {
279 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
280 } finally {
281 Binder.restoreCallingIdentity(token);
282 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700283 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700284 updateState(DetailedState.IDLE, "prepare");
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700285 return true;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700286 }
287
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400288 private int getAppUid(String app) {
289 if (app == VpnConfig.LEGACY_VPN) {
290 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700291 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400292 PackageManager pm = mContext.getPackageManager();
293 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700294 try {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400295 result = pm.getPackageUid(app, mUserId);
296 } catch (NameNotFoundException e) {
297 result = -1;
298 }
299 return result;
300 }
301
302 public NetworkInfo getNetworkInfo() {
303 return mNetworkInfo;
304 }
305
306 private void agentConnect() {
307 LinkProperties lp = new LinkProperties();
308 lp.setInterfaceName(mInterface);
309 boolean hasDefaultRoute = false;
310 for (RouteInfo route : mConfig.routes) {
311 lp.addRoute(route);
312 if (route.isDefaultRoute()) hasDefaultRoute = true;
313 }
314 if (hasDefaultRoute) {
315 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
316 } else {
317 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
318 }
319 if (mConfig.dnsServers != null) {
320 for (String dnsServer : mConfig.dnsServers) {
321 lp.addDnsServer(InetAddress.parseNumericAddress(dnsServer));
322 }
323 }
324 // Concatenate search domains into a string.
325 StringBuilder buffer = new StringBuilder();
326 if (mConfig.searchDomains != null) {
327 for (String domain : mConfig.searchDomains) {
328 buffer.append(domain).append(' ');
329 }
330 }
331 lp.setDomains(buffer.toString().trim());
332 mNetworkInfo.setIsAvailable(true);
333 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
334 long token = Binder.clearCallingIdentity();
335 try {
336 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
337 mNetworkInfo, mNetworkCapabilities, lp, 0) {
338 public void unwanted() {
339 // We are user controlled, not driven by NetworkRequest.
340 };
341 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700342 } finally {
343 Binder.restoreCallingIdentity(token);
344 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400345 addVpnUserLocked(mUserId);
346 // If we are owner assign all Restricted Users to this VPN
347 if (mUserId == UserHandle.USER_OWNER) {
348 token = Binder.clearCallingIdentity();
349 List<UserInfo> users;
350 try {
351 users = UserManager.get(mContext).getUsers();
352 } finally {
353 Binder.restoreCallingIdentity(token);
354 }
355 for (UserInfo user : users) {
356 if (user.isRestricted()) {
357 addVpnUserLocked(user.id);
358 }
359 }
360 }
361 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
362 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700363
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400364 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
365 networkInfo.setIsAvailable(false);
366 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
367 if (networkAgent != null) {
368 networkAgent.sendNetworkInfo(networkInfo);
369 }
370 }
371
372 private void agentDisconnect(NetworkAgent networkAgent) {
373 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
374 agentDisconnect(networkInfo, networkAgent);
375 }
376
377 private void agentDisconnect() {
378 if (mNetworkInfo.isConnected()) {
379 agentDisconnect(mNetworkInfo, mNetworkAgent);
380 mNetworkAgent = null;
381 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700382 }
383
384 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700385 * Establish a VPN network and return the file descriptor of the VPN
386 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700387 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700388 *
389 * @param config The parameters to configure the network.
390 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700391 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700392 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700393 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700394 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400395 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700396 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700397 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700398 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700399 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
400 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700401 long token = Binder.clearCallingIdentity();
402 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700403 // Restricted users are not allowed to create VPNs, they are tied to Owner
404 UserInfo user = mgr.getUserInfo(mUserId);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400405 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700406 throw new SecurityException("Restricted users cannot establish VPNs");
407 }
408
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700409 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
410 null, 0, mUserId);
411 if (info == null) {
412 throw new SecurityException("Cannot find " + config.user);
413 }
414 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
415 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
416 }
417 } catch (RemoteException e) {
418 throw new SecurityException("Cannot find " + config.user);
419 } finally {
420 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700421 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700422
Chad Brubaker850eb672014-03-21 21:02:47 +0000423 // Save the old config in case we need to go back.
424 VpnConfig oldConfig = mConfig;
425 String oldInterface = mInterface;
426 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400427 NetworkAgent oldNetworkAgent = mNetworkAgent;
428 mNetworkAgent = null;
429 List<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000430
Chia-chi Yehe9107902011-07-02 01:48:50 -0700431 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700432 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700433 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700434 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700435 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700436
Chad Brubakerc2865192013-07-10 14:46:23 -0700437 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700438 StringBuilder builder = new StringBuilder();
439 for (LinkAddress address : config.addresses) {
440 builder.append(" " + address);
441 }
442 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700443 throw new IllegalArgumentException("At least one address must be specified");
444 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700445 Connection connection = new Connection();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700446 if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
447 new UserHandle(mUserId))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700448 throw new IllegalStateException("Cannot bind " + config.user);
449 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000450
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700451 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700452 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700453
454 // Fill more values.
455 config.user = mPackage;
456 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700457 config.startTime = SystemClock.elapsedRealtime();
458 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000459
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700460 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400461 mVpnUsers = new ArrayList<UidRange>();
462 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000463
464 if (oldConnection != null) {
465 mContext.unbindService(oldConnection);
466 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400467 // Remove the old tun's user forwarding rules
468 // The new tun's user rules have already been added so they will take over
469 // as rules are deleted. This prevents data leakage as the rules are moved over.
470 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000471 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000472 jniReset(oldInterface);
473 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700474
475 try {
476 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
477 } catch (IOException e) {
478 throw new IllegalStateException(
479 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
480 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000481 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000482 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400483 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000484 // restore old state
485 mConfig = oldConfig;
486 mConnection = oldConnection;
487 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400488 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000489 mInterface = oldInterface;
490 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700491 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000492 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
493
Jeff Sharkey899223b2012-08-04 15:24:58 -0700494 // TODO: ensure that contract class eventually marks as connected
495 updateState(DetailedState.AUTHENTICATING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700496 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700497 }
498
Chad Brubakerc2865192013-07-10 14:46:23 -0700499 private boolean isRunningLocked() {
500 return mVpnUsers != null;
501 }
502
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400503 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Chad Brubakerc2865192013-07-10 14:46:23 -0700504 private void addVpnUserLocked(int user) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700505 if (!isRunningLocked()) {
506 throw new IllegalStateException("VPN is not active");
507 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700508
Chad Brubakerc2865192013-07-10 14:46:23 -0700509 // add the user
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400510 mVpnUsers.add(UidRange.createForUser(user));
Chad Brubakerc2865192013-07-10 14:46:23 -0700511
512 // show the notification
513 if (!mPackage.equals(VpnConfig.LEGACY_VPN)) {
514 // Load everything for the user's notification
515 PackageManager pm = mContext.getPackageManager();
516 ApplicationInfo app = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400517 final long token = Binder.clearCallingIdentity();
Chad Brubakerc2865192013-07-10 14:46:23 -0700518 try {
519 app = AppGlobals.getPackageManager().getApplicationInfo(mPackage, 0, mUserId);
520 } catch (RemoteException e) {
521 throw new IllegalStateException("Invalid application");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400522 } finally {
523 Binder.restoreCallingIdentity(token);
Chad Brubakerc2865192013-07-10 14:46:23 -0700524 }
525 String label = app.loadLabel(pm).toString();
526 // Load the icon and convert it into a bitmap.
527 Drawable icon = app.loadIcon(pm);
528 Bitmap bitmap = null;
529 if (icon.getIntrinsicWidth() > 0 && icon.getIntrinsicHeight() > 0) {
530 int width = mContext.getResources().getDimensionPixelSize(
531 android.R.dimen.notification_large_icon_width);
532 int height = mContext.getResources().getDimensionPixelSize(
533 android.R.dimen.notification_large_icon_height);
534 icon.setBounds(0, 0, width, height);
535 bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
536 Canvas c = new Canvas(bitmap);
537 icon.draw(c);
538 c.setBitmap(null);
539 }
540 showNotification(label, bitmap, user);
541 } else {
542 showNotification(null, null, user);
543 }
544 }
545
546 private void removeVpnUserLocked(int user) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700547 if (!isRunningLocked()) {
548 throw new IllegalStateException("VPN is not active");
549 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400550 UidRange uidRange = UidRange.createForUser(user);
551 if (mNetworkAgent != null) {
552 mNetworkAgent.removeUidRanges(new UidRange[] { uidRange });
553 }
554 mVpnUsers.remove(uidRange);
Chad Brubakerc2865192013-07-10 14:46:23 -0700555 hideNotification(user);
556 }
557
558 private void onUserAdded(int userId) {
559 // If the user is restricted tie them to the owner's VPN
560 synchronized(Vpn.this) {
561 UserManager mgr = UserManager.get(mContext);
562 UserInfo user = mgr.getUserInfo(userId);
563 if (user.isRestricted()) {
564 try {
565 addVpnUserLocked(userId);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400566 if (mNetworkAgent != null) {
567 UidRange uidRange = UidRange.createForUser(userId);
568 mNetworkAgent.addUidRanges(new UidRange[] { uidRange });
569 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700570 } catch (Exception e) {
571 Log.wtf(TAG, "Failed to add restricted user to owner", e);
572 }
573 }
574 }
575 }
576
577 private void onUserRemoved(int userId) {
578 // clean up if restricted
579 synchronized(Vpn.this) {
580 UserManager mgr = UserManager.get(mContext);
581 UserInfo user = mgr.getUserInfo(userId);
582 if (user.isRestricted()) {
583 try {
584 removeVpnUserLocked(userId);
585 } catch (Exception e) {
586 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
587 }
588 }
589 }
590 }
591
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700592 /**
593 * Return the configuration of the currently running VPN.
594 */
595 public VpnConfig getVpnConfig() {
596 enforceControlPermission();
597 return mConfig;
598 }
599
Jeff Sharkey899223b2012-08-04 15:24:58 -0700600 @Deprecated
601 public synchronized void interfaceStatusChanged(String iface, boolean up) {
602 try {
603 mObserver.interfaceStatusChanged(iface, up);
604 } catch (RemoteException e) {
605 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700606 }
607 }
608
Jeff Sharkey899223b2012-08-04 15:24:58 -0700609 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
610 @Override
611 public void interfaceStatusChanged(String interfaze, boolean up) {
612 synchronized (Vpn.this) {
613 if (!up && mLegacyVpnRunner != null) {
614 mLegacyVpnRunner.check(interfaze);
615 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700616 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700617 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700618
Jeff Sharkey899223b2012-08-04 15:24:58 -0700619 @Override
620 public void interfaceRemoved(String interfaze) {
621 synchronized (Vpn.this) {
622 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400623 for (UidRange uidRange : mVpnUsers) {
624 hideNotification(uidRange.getStartUser());
Jeff Sharkey899223b2012-08-04 15:24:58 -0700625 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400626 mVpnUsers = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700627 mInterface = null;
628 if (mConnection != null) {
629 mContext.unbindService(mConnection);
630 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400631 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700632 } else if (mLegacyVpnRunner != null) {
633 mLegacyVpnRunner.exit();
634 mLegacyVpnRunner = null;
635 }
636 }
637 }
638 }
639 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700640
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700641 private void enforceControlPermission() {
642 // System user is allowed to control VPN.
643 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
644 return;
645 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700646 int appId = UserHandle.getAppId(Binder.getCallingUid());
647 final long token = Binder.clearCallingIdentity();
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700648 try {
Nick Kralevich212a1952013-10-18 17:48:39 -0700649 // System VPN dialogs are also allowed to control VPN.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700650 PackageManager pm = mContext.getPackageManager();
651 ApplicationInfo app = pm.getApplicationInfo(VpnConfig.DIALOGS_PACKAGE, 0);
Nick Kralevich212a1952013-10-18 17:48:39 -0700652 if (((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) && (appId == app.uid)) {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700653 return;
654 }
655 } catch (Exception e) {
656 // ignore
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700657 } finally {
658 Binder.restoreCallingIdentity(token);
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700659 }
660
661 throw new SecurityException("Unauthorized Caller");
662 }
663
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700664 private class Connection implements ServiceConnection {
665 private IBinder mService;
666
667 @Override
668 public void onServiceConnected(ComponentName name, IBinder service) {
669 mService = service;
670 }
671
672 @Override
673 public void onServiceDisconnected(ComponentName name) {
674 mService = null;
675 }
676 }
677
Chad Brubakerc2865192013-07-10 14:46:23 -0700678 private void showNotification(String label, Bitmap icon, int user) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700679 if (!mEnableNotif) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400680 final long token = Binder.clearCallingIdentity();
681 try {
682 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700683
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400684 NotificationManager nm = (NotificationManager)
685 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700686
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400687 if (nm != null) {
688 String title = (label == null) ? mContext.getString(R.string.vpn_title) :
689 mContext.getString(R.string.vpn_title_long, label);
690 String text = (mConfig.session == null) ? mContext.getString(R.string.vpn_text) :
691 mContext.getString(R.string.vpn_text_long, mConfig.session);
Chia-chi Yeha4b87b52011-06-30 23:21:55 -0700692
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400693 Notification notification = new Notification.Builder(mContext)
694 .setSmallIcon(R.drawable.vpn_connected)
695 .setLargeIcon(icon)
696 .setContentTitle(title)
697 .setContentText(text)
698 .setContentIntent(mStatusIntent)
699 .setDefaults(0)
700 .setOngoing(true)
701 .build();
702 nm.notifyAsUser(null, R.drawable.vpn_connected, notification, new UserHandle(user));
703 }
704 } finally {
705 Binder.restoreCallingIdentity(token);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700706 }
707 }
708
Chad Brubakerc2865192013-07-10 14:46:23 -0700709 private void hideNotification(int user) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700710 if (!mEnableNotif) return;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700711 mStatusIntent = null;
712
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700713 NotificationManager nm = (NotificationManager)
714 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
715
716 if (nm != null) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400717 final long token = Binder.clearCallingIdentity();
718 try {
719 nm.cancelAsUser(null, R.drawable.vpn_connected, new UserHandle(user));
720 } finally {
721 Binder.restoreCallingIdentity(token);
722 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700723 }
724 }
725
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700726 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700727 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700728 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700729 private native void jniReset(String interfaze);
730 private native int jniCheck(String interfaze);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700731
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900732 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
733 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700734 // Currently legacy VPN only works on IPv4.
735 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900736 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700737 }
738 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700739
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900740 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700741 }
742
743 /**
744 * Start legacy VPN, controlling native daemons as needed. Creates a
745 * secondary thread to perform connection work, returning quickly.
746 */
747 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800748 enforceControlPermission();
Kenny Rootb9594ce2013-02-14 10:18:38 -0800749 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700750 throw new IllegalStateException("KeyStore isn't unlocked");
751 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400752 UserManager mgr = UserManager.get(mContext);
753 UserInfo user = mgr.getUserInfo(mUserId);
754 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
755 throw new SecurityException("Restricted users cannot establish VPNs");
756 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700757
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900758 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
759 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
760 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700761
762 // Load certificates.
763 String privateKey = "";
764 String userCert = "";
765 String caCert = "";
766 String serverCert = "";
767 if (!profile.ipsecUserCert.isEmpty()) {
768 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
769 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700770 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700771 }
772 if (!profile.ipsecCaCert.isEmpty()) {
773 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700774 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700775 }
776 if (!profile.ipsecServerCert.isEmpty()) {
777 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700778 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700779 }
780 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
781 throw new IllegalStateException("Cannot load credentials");
782 }
783
784 // Prepare arguments for racoon.
785 String[] racoon = null;
786 switch (profile.type) {
787 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
788 racoon = new String[] {
789 iface, profile.server, "udppsk", profile.ipsecIdentifier,
790 profile.ipsecSecret, "1701",
791 };
792 break;
793 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
794 racoon = new String[] {
795 iface, profile.server, "udprsa", privateKey, userCert,
796 caCert, serverCert, "1701",
797 };
798 break;
799 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
800 racoon = new String[] {
801 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
802 profile.ipsecSecret, profile.username, profile.password, "", gateway,
803 };
804 break;
805 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
806 racoon = new String[] {
807 iface, profile.server, "xauthrsa", privateKey, userCert,
808 caCert, serverCert, profile.username, profile.password, "", gateway,
809 };
810 break;
811 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
812 racoon = new String[] {
813 iface, profile.server, "hybridrsa",
814 caCert, serverCert, profile.username, profile.password, "", gateway,
815 };
816 break;
817 }
818
819 // Prepare arguments for mtpd.
820 String[] mtpd = null;
821 switch (profile.type) {
822 case VpnProfile.TYPE_PPTP:
823 mtpd = new String[] {
824 iface, "pptp", profile.server, "1723",
825 "name", profile.username, "password", profile.password,
826 "linkname", "vpn", "refuse-eap", "nodefaultroute",
827 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
828 (profile.mppe ? "+mppe" : "nomppe"),
829 };
830 break;
831 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
832 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
833 mtpd = new String[] {
834 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
835 "name", profile.username, "password", profile.password,
836 "linkname", "vpn", "refuse-eap", "nodefaultroute",
837 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
838 };
839 break;
840 }
841
842 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700843 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700844 config.user = profile.key;
845 config.interfaze = iface;
846 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700847
848 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700849 if (!profile.dnsServers.isEmpty()) {
850 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
851 }
852 if (!profile.searchDomains.isEmpty()) {
853 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
854 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700855 startLegacyVpn(config, racoon, mtpd);
856 }
857
858 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
859 stopLegacyVpn();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700860
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700861 // Prepare for the new request. This also checks the caller.
862 prepare(null, VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700863 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700864
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700865 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700866 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
867 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700868 }
869
Jeff Sharkey899223b2012-08-04 15:24:58 -0700870 public synchronized void stopLegacyVpn() {
871 if (mLegacyVpnRunner != null) {
872 mLegacyVpnRunner.exit();
873 mLegacyVpnRunner = null;
874
875 synchronized (LegacyVpnRunner.TAG) {
876 // wait for old thread to completely finish before spinning up
877 // new instance, otherwise state updates can be out of order.
878 }
879 }
880 }
881
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700882 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700883 * Return the information of the current ongoing legacy VPN.
884 */
885 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700886 // Check if the caller is authorized.
887 enforceControlPermission();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700888 if (mLegacyVpnRunner == null) return null;
889
890 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -0700891 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700892 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
893 if (mNetworkInfo.isConnected()) {
894 info.intent = mStatusIntent;
895 }
896 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700897 }
898
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700899 public VpnConfig getLegacyVpnConfig() {
900 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700901 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700902 } else {
903 return null;
904 }
905 }
906
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700907 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700908 * Bringing up a VPN connection takes time, and that is all this thread
909 * does. Here we have plenty of time. The only thing we need to take
910 * care of is responding to interruptions as soon as possible. Otherwise
911 * requests will be piled up. This can be done in a Handler as a state
912 * machine, but it is much easier to read in the current form.
913 */
914 private class LegacyVpnRunner extends Thread {
915 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700916
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700917 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700918 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700919 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700920 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700921 private final AtomicInteger mOuterConnection =
922 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700923
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700924 private long mTimer = -1;
925
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700926 /**
927 * Watch for the outer connection (passing in the constructor) going away.
928 */
929 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
930 @Override
931 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -0700932 if (!mEnableTeardown) return;
933
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700934 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
935 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
936 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
937 NetworkInfo info = (NetworkInfo)intent.getExtra(
938 ConnectivityManager.EXTRA_NETWORK_INFO);
939 if (info != null && !info.isConnectedOrConnecting()) {
940 try {
941 mObserver.interfaceStatusChanged(mOuterInterface, false);
942 } catch (RemoteException e) {}
943 }
944 }
945 }
946 }
947 };
948
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700949 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700950 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700951 mConfig = config;
952 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -0700953 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700954 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700955 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700956
957 // This is the interface which VPN is running on,
958 // mConfig.interfaze will change to point to OUR
959 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700960 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700961 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700962 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700963 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700964
965 try {
966 mOuterConnection.set(
967 mConnService.findConnectionTypeForIface(mOuterInterface));
968 } catch (Exception e) {
969 mOuterConnection.set(ConnectivityManager.TYPE_NONE);
970 }
971
972 IntentFilter filter = new IntentFilter();
973 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
974 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700975 }
976
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700977 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700978 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700979 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
980 exit();
981 }
982 }
983
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700984 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700985 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700986 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700987 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -0700988 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700989 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400990 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700991 try {
992 mContext.unregisterReceiver(mBroadcastReceiver);
993 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700994 }
995
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700996 @Override
997 public void run() {
998 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700999 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001000 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001001 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001002 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001003 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001004 }
1005 }
1006
1007 private void checkpoint(boolean yield) throws InterruptedException {
1008 long now = SystemClock.elapsedRealtime();
1009 if (mTimer == -1) {
1010 mTimer = now;
1011 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001012 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001013 Thread.sleep(yield ? 200 : 1);
1014 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001015 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001016 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001017 }
1018 }
1019
1020 private void execute() {
1021 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001022 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001023 try {
1024 // Initialize the timer.
1025 checkpoint(false);
1026
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001027 // Wait for the daemons to stop.
1028 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001029 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001030 checkpoint(true);
1031 }
1032 }
1033
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001034 // Clear the previous state.
1035 File state = new File("/data/misc/vpn/state");
1036 state.delete();
1037 if (state.exists()) {
1038 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001039 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001040 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001041 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001042
Chia-chi Yehe9107902011-07-02 01:48:50 -07001043 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001044 boolean restart = false;
1045 for (String[] arguments : mArguments) {
1046 restart = restart || (arguments != null);
1047 }
1048 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001049 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001050 return;
1051 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001052 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001053
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001054 // Start the daemon with arguments.
1055 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001056 String[] arguments = mArguments[i];
1057 if (arguments == null) {
1058 continue;
1059 }
1060
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001061 // Start the daemon.
1062 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001063 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001064
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001065 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001066 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001067 checkpoint(true);
1068 }
1069
1070 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001071 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001072 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001073 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001074
1075 // Wait for the socket to connect.
1076 while (true) {
1077 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001078 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001079 break;
1080 } catch (Exception e) {
1081 // ignore
1082 }
1083 checkpoint(true);
1084 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001085 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001086
1087 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001088 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001089 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001090 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001091 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001092 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001093 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001094 out.write(bytes.length >> 8);
1095 out.write(bytes.length);
1096 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001097 checkpoint(false);
1098 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001099 out.write(0xFF);
1100 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001101 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001102
1103 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001104 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001105 while (true) {
1106 try {
1107 if (in.read() == -1) {
1108 break;
1109 }
1110 } catch (Exception e) {
1111 // ignore
1112 }
1113 checkpoint(true);
1114 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001115 }
1116
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001117 // Wait for the daemons to create the new state.
1118 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001119 // Check if a running daemon is dead.
1120 for (int i = 0; i < mDaemons.length; ++i) {
1121 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001122 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001123 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001124 }
1125 }
1126 checkpoint(true);
1127 }
1128
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001129 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001130 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001131 if (parameters.length != 6) {
1132 throw new IllegalStateException("Cannot parse the state");
1133 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001134
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001135 // Set the interface and the addresses in the config.
1136 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001137
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001138 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001139 // Set the routes if they are not set in the config.
1140 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001141 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001142 }
1143
1144 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001145 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001146 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001147 if (!dnsServers.isEmpty()) {
1148 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1149 }
1150 }
1151
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001152 // Set the search domains if they are not set in the config.
1153 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1154 String searchDomains = parameters[4].trim();
1155 if (!searchDomains.isEmpty()) {
1156 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1157 }
1158 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001159
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001160 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001161 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001162 // Set the start time
1163 mConfig.startTime = SystemClock.elapsedRealtime();
1164
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001165 // Check if the thread is interrupted while we are waiting.
1166 checkpoint(false);
1167
Chia-chi Yehe9107902011-07-02 01:48:50 -07001168 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001169 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001170 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001171 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001172
1173 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001174 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001175 mVpnUsers = new ArrayList<UidRange>();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001176
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001177 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001178
1179 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001180 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001181 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001182 Log.i(TAG, "Aborting", e);
Chia-chi Yehe9107902011-07-02 01:48:50 -07001183 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001184 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001185 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001186 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001187 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001188 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001189 }
1190 }
1191
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001192 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001193 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001194 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001195 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001196 }
1197 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001198
1199 /**
1200 * Monitor the daemons we started, moving to disconnected state if the
1201 * underlying services fail.
1202 */
1203 private void monitorDaemons() {
1204 if (!mNetworkInfo.isConnected()) {
1205 return;
1206 }
1207
1208 try {
1209 while (true) {
1210 Thread.sleep(2000);
1211 for (int i = 0; i < mDaemons.length; i++) {
1212 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1213 return;
1214 }
1215 }
1216 }
1217 } catch (InterruptedException e) {
1218 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1219 } finally {
1220 for (String daemon : mDaemons) {
1221 SystemService.stop(daemon);
1222 }
1223
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001224 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001225 }
1226 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001227 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001228}