blob: ad7c0aaf28dda71387072c53cefe72d0bd03dcd9 [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;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070033import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070034import android.content.pm.UserInfo;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070035import android.graphics.Bitmap;
36import android.graphics.Canvas;
37import android.graphics.drawable.Drawable;
Jeff Sharkey899223b2012-08-04 15:24:58 -070038import android.net.BaseNetworkStateTracker;
39import android.net.ConnectivityManager;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070040import android.net.IConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070041import android.net.INetworkManagementEventObserver;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070042import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070043import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070044import android.net.LocalSocket;
45import android.net.LocalSocketAddress;
Jeff Sharkey899223b2012-08-04 15:24:58 -070046import android.net.NetworkInfo;
Chad Brubakerc0234532014-02-14 13:24:29 -080047import android.net.NetworkUtils;
Jeff Sharkey82f85212012-08-24 11:17:25 -070048import android.net.RouteInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070049import android.net.NetworkInfo.DetailedState;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070050import android.os.Binder;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080051import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070052import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070053import android.os.INetworkManagementService;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070054import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070055import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070056import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070057import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070058import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070059import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070060import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070061import android.os.UserManager;
Jeff Sharkey82f85212012-08-24 11:17:25 -070062import android.security.Credentials;
63import android.security.KeyStore;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070064import android.util.Log;
Chad Brubakerc2865192013-07-10 14:46:23 -070065import android.util.SparseBooleanArray;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070066
Chad Brubakerc2865192013-07-10 14:46:23 -070067import com.android.internal.annotations.GuardedBy;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070068import com.android.internal.R;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070069import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070070import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -070071import com.android.internal.net.VpnProfile;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070072import com.android.server.ConnectivityService.VpnCallback;
Jeff Sharkey899223b2012-08-04 15:24:58 -070073import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070074
Chia-chi Yeh97a61562011-07-14 15:05:05 -070075import java.io.File;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070076import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070077import java.io.OutputStream;
Chad Brubakerc0234532014-02-14 13:24:29 -080078import java.net.InetAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070079import java.net.Inet4Address;
Elliott Hughesd396a442013-06-28 16:24:48 -070080import java.nio.charset.StandardCharsets;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070081import java.util.Arrays;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070082import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070083
Jeff Sharkey065b2992012-08-05 14:16:48 -070084import libcore.io.IoUtils;
85
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070086/**
87 * @hide
88 */
Jeff Sharkey899223b2012-08-04 15:24:58 -070089public class Vpn extends BaseNetworkStateTracker {
90 private static final String TAG = "Vpn";
91 private static final boolean LOGD = true;
92
93 // TODO: create separate trackers for each unique VPN to support
94 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070095
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070096 private final VpnCallback mCallback;
97
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -070098 private String mPackage = VpnConfig.LEGACY_VPN;
99 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700100 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700101 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700102 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700103 private volatile boolean mEnableNotif = true;
104 private volatile boolean mEnableTeardown = true;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700105 private final IConnectivityManager mConnService;
Chad Brubakerc2865192013-07-10 14:46:23 -0700106 private VpnConfig mConfig;
107
108 /* list of users using this VPN. */
109 @GuardedBy("this")
110 private SparseBooleanArray mVpnUsers = null;
111 private BroadcastReceiver mUserIntentReceiver = null;
112
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700113 private final int mUserId;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700114
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700115 public Vpn(Context context, VpnCallback callback, INetworkManagementService netService,
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700116 IConnectivityManager connService, int userId) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700117 // TODO: create dedicated TYPE_VPN network type
118 super(ConnectivityManager.TYPE_DUMMY);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700119 mContext = context;
120 mCallback = callback;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700121 mConnService = connService;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700122 mUserId = userId;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700123
124 try {
125 netService.registerObserver(mObserver);
126 } catch (RemoteException e) {
127 Log.wtf(TAG, "Problem registering observer", e);
128 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700129 if (userId == UserHandle.USER_OWNER) {
130 // Owner's VPN also needs to handle restricted users
131 mUserIntentReceiver = new BroadcastReceiver() {
132 @Override
133 public void onReceive(Context context, Intent intent) {
134 final String action = intent.getAction();
135 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
136 UserHandle.USER_NULL);
137 if (userId == UserHandle.USER_NULL) return;
138
139 if (Intent.ACTION_USER_ADDED.equals(action)) {
140 onUserAdded(userId);
141 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
142 onUserRemoved(userId);
143 }
144 }
145 };
146
147 IntentFilter intentFilter = new IntentFilter();
148 intentFilter.addAction(Intent.ACTION_USER_ADDED);
149 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
150 mContext.registerReceiverAsUser(
151 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
152 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700153 }
154
Jeff Sharkey57666932013-04-30 17:01:57 -0700155 /**
156 * Set if this object is responsible for showing its own notifications. When
157 * {@code false}, notifications are handled externally by someone else.
158 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700159 public void setEnableNotifications(boolean enableNotif) {
160 mEnableNotif = enableNotif;
161 }
162
Jeff Sharkey57666932013-04-30 17:01:57 -0700163 /**
164 * Set if this object is responsible for watching for {@link NetworkInfo}
165 * teardown. When {@code false}, teardown is handled externally by someone
166 * else.
167 */
168 public void setEnableTeardown(boolean enableTeardown) {
169 mEnableTeardown = enableTeardown;
170 }
171
Jeff Sharkey899223b2012-08-04 15:24:58 -0700172 @Override
173 protected void startMonitoringInternal() {
174 // Ignored; events are sent through callbacks for now
175 }
176
177 @Override
178 public boolean teardown() {
179 // TODO: finish migration to unique tracker for each VPN
180 throw new UnsupportedOperationException();
181 }
182
183 @Override
184 public boolean reconnect() {
185 // TODO: finish migration to unique tracker for each VPN
186 throw new UnsupportedOperationException();
187 }
188
189 @Override
190 public String getTcpBufferSizesPropName() {
191 return PROP_TCP_BUFFER_UNKNOWN;
192 }
193
194 /**
195 * Update current state, dispaching event to listeners.
196 */
197 private void updateState(DetailedState detailedState, String reason) {
198 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
199 mNetworkInfo.setDetailedState(detailedState, reason, null);
200 mCallback.onStateChanged(new NetworkInfo(mNetworkInfo));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700201 }
202
203 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700204 * Prepare for a VPN application. This method is designed to solve
205 * race conditions. It first compares the current prepared package
206 * with {@code oldPackage}. If they are the same, the prepared
207 * package is revoked and replaced with {@code newPackage}. If
208 * {@code oldPackage} is {@code null}, the comparison is omitted.
209 * If {@code newPackage} is the same package or {@code null}, the
210 * revocation is omitted. This method returns {@code true} if the
211 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700212 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700213 * Legacy VPN is handled specially since it is not a real package.
214 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
215 * it can be revoked by itself.
216 *
217 * @param oldPackage The package name of the old VPN application.
218 * @param newPackage The package name of the new VPN application.
219 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700220 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700221 public synchronized boolean prepare(String oldPackage, String newPackage) {
222 // Return false if the package does not match.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700223 if (oldPackage != null && !oldPackage.equals(mPackage)) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700224 return false;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700225 }
226
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700227 // Return true if we do not need to revoke.
228 if (newPackage == null ||
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700229 (newPackage.equals(mPackage) && !newPackage.equals(VpnConfig.LEGACY_VPN))) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700230 return true;
231 }
232
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700233 // Check if the caller is authorized.
234 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700235
Chia-chi Yehe9107902011-07-02 01:48:50 -0700236 // Reset the interface and hide the notification.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700237 if (mInterface != null) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700238 final long token = Binder.clearCallingIdentity();
239 try {
240 mCallback.restore();
Chad Brubakerc2865192013-07-10 14:46:23 -0700241 final int size = mVpnUsers.size();
Robert Greenwalt69887e82013-09-24 11:05:57 -0700242 final boolean forwardDns = (mConfig.dnsServers != null &&
243 mConfig.dnsServers.size() != 0);
Chad Brubakerc2865192013-07-10 14:46:23 -0700244 for (int i = 0; i < size; i++) {
245 int user = mVpnUsers.keyAt(i);
Robert Greenwalt69887e82013-09-24 11:05:57 -0700246 mCallback.clearUserForwarding(mInterface, user, forwardDns);
Chad Brubakerc2865192013-07-10 14:46:23 -0700247 hideNotification(user);
248 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700249
250 mCallback.clearMarkedForwarding(mInterface);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700251 } finally {
252 Binder.restoreCallingIdentity(token);
253 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700254 jniReset(mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700255 mInterface = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700256 mVpnUsers = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700257 }
258
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700259 // Revoke the connection or stop LegacyVpnRunner.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700260 if (mConnection != null) {
261 try {
262 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
263 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
264 } catch (Exception e) {
265 // ignore
266 }
267 mContext.unbindService(mConnection);
268 mConnection = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700269 } else if (mLegacyVpnRunner != null) {
270 mLegacyVpnRunner.exit();
271 mLegacyVpnRunner = null;
272 }
273
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700274 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
275 mPackage = newPackage;
Chad Brubakerc2865192013-07-10 14:46:23 -0700276 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700277 updateState(DetailedState.IDLE, "prepare");
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700278 return true;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700279 }
280
281 /**
Chad Brubakerbcf12b32014-02-11 14:18:56 -0800282 * Protect a socket from VPN rules by binding it to the main routing table.
283 * The socket is NOT closed by this method.
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700284 *
285 * @param socket The socket to be bound.
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700286 */
Chad Brubakerbcf12b32014-02-11 14:18:56 -0800287 public void protect(ParcelFileDescriptor socket) throws Exception {
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700288
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700289 PackageManager pm = mContext.getPackageManager();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700290 int appUid = pm.getPackageUid(mPackage, mUserId);
291 if (Binder.getCallingUid() != appUid) {
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700292 throw new SecurityException("Unauthorized Caller");
293 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700294 // protect the socket from routing rules
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700295 final long token = Binder.clearCallingIdentity();
296 try {
297 mCallback.protect(socket);
298 } finally {
299 Binder.restoreCallingIdentity(token);
300 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700301
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700302 }
303
304 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700305 * Establish a VPN network and return the file descriptor of the VPN
306 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700307 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700308 *
309 * @param config The parameters to configure the network.
310 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700311 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700312 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700313 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700314 UserManager mgr = UserManager.get(mContext);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700315 PackageManager pm = mContext.getPackageManager();
316 ApplicationInfo app = null;
317 try {
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700318 app = AppGlobals.getPackageManager().getApplicationInfo(mPackage, 0, mUserId);
319 if (Binder.getCallingUid() != app.uid) {
320 return null;
321 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700322 } catch (Exception e) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700323 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700324 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700325 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700326 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
327 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700328 long token = Binder.clearCallingIdentity();
329 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700330 // Restricted users are not allowed to create VPNs, they are tied to Owner
331 UserInfo user = mgr.getUserInfo(mUserId);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400332 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700333 throw new SecurityException("Restricted users cannot establish VPNs");
334 }
335
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700336 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
337 null, 0, mUserId);
338 if (info == null) {
339 throw new SecurityException("Cannot find " + config.user);
340 }
341 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
342 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
343 }
344 } catch (RemoteException e) {
345 throw new SecurityException("Cannot find " + config.user);
346 } finally {
347 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700348 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700349
Chad Brubaker850eb672014-03-21 21:02:47 +0000350 // Save the old config in case we need to go back.
351 VpnConfig oldConfig = mConfig;
352 String oldInterface = mInterface;
353 Connection oldConnection = mConnection;
354 SparseBooleanArray oldUsers = mVpnUsers;
355
Chia-chi Yehe9107902011-07-02 01:48:50 -0700356 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700357 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700358 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700359 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700360 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700361
Chad Brubakerc2865192013-07-10 14:46:23 -0700362 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700363 StringBuilder builder = new StringBuilder();
364 for (LinkAddress address : config.addresses) {
365 builder.append(" " + address);
366 }
367 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700368 throw new IllegalArgumentException("At least one address must be specified");
369 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700370 Connection connection = new Connection();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700371 if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
372 new UserHandle(mUserId))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700373 throw new IllegalStateException("Cannot bind " + config.user);
374 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000375
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700376 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700377 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700378
379 // Fill more values.
380 config.user = mPackage;
381 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700382 config.startTime = SystemClock.elapsedRealtime();
383 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000384
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700385 // Set up forwarding and DNS rules.
Chad Brubakerc2865192013-07-10 14:46:23 -0700386 mVpnUsers = new SparseBooleanArray();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700387 token = Binder.clearCallingIdentity();
388 try {
389 mCallback.setMarkedForwarding(mInterface);
Chad Brubaker850eb672014-03-21 21:02:47 +0000390 mCallback.setRoutes(mInterface, config.routes);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700391 mCallback.override(mInterface, config.dnsServers, config.searchDomains);
Chad Brubakerc2865192013-07-10 14:46:23 -0700392 addVpnUserLocked(mUserId);
Chad Brubaker850eb672014-03-21 21:02:47 +0000393 // If we are owner assign all Restricted Users to this VPN
394 if (mUserId == UserHandle.USER_OWNER) {
395 for (UserInfo user : mgr.getUsers()) {
396 if (user.isRestricted()) {
397 try {
398 addVpnUserLocked(user.id);
399 } catch (Exception e) {
400 Log.wtf(TAG, "Failed to add user " + user.id + " to owner's VPN");
401 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700402 }
403 }
404 }
405 } finally {
406 Binder.restoreCallingIdentity(token);
407 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000408
409 if (oldConnection != null) {
410 mContext.unbindService(oldConnection);
411 }
412 if (oldInterface != null && !oldInterface.equals(interfaze)) {
413 // Remove the old tun's user forwarding rules
414 // The new tun's user rules have already been added so they will take over
415 // as rules are deleted. This prevents data leakage as the rules are moved over.
416 token = Binder.clearCallingIdentity();
417 try {
418 final int size = oldUsers.size();
419 final boolean forwardDns = (oldConfig.dnsServers != null &&
420 oldConfig.dnsServers.size() != 0);
421 for (int i = 0; i < size; i++) {
422 int user = oldUsers.keyAt(i);
423 mCallback.clearUserForwarding(oldInterface, user, forwardDns);
424 }
425 mCallback.clearMarkedForwarding(oldInterface);
426 } finally {
427 Binder.restoreCallingIdentity(token);
428 }
429 jniReset(oldInterface);
430 }
431 } catch (RuntimeException e) {
432 updateState(DetailedState.FAILED, "establish");
433 IoUtils.closeQuietly(tun);
434 // make sure marked forwarding is cleared if it was set
435 token = Binder.clearCallingIdentity();
436 try {
437 mCallback.clearMarkedForwarding(mInterface);
438 } catch (Exception ingored) {
439 // ignored
440 } finally {
441 Binder.restoreCallingIdentity(token);
442 }
443 // restore old state
444 mConfig = oldConfig;
445 mConnection = oldConnection;
446 mVpnUsers = oldUsers;
447 mInterface = oldInterface;
448 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700449 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000450 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
451
Jeff Sharkey899223b2012-08-04 15:24:58 -0700452 // TODO: ensure that contract class eventually marks as connected
453 updateState(DetailedState.AUTHENTICATING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700454 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700455 }
456
Chad Brubakerc0234532014-02-14 13:24:29 -0800457 /**
458 * Check if a given address is covered by the VPN's routing rules.
459 */
460 public boolean isAddressCovered(InetAddress address) {
461 synchronized (Vpn.this) {
462 if (!isRunningLocked()) {
463 return false;
464 }
465 return RouteInfo.selectBestRoute(mConfig.routes, address) != null;
466 }
467 }
468
Chad Brubakerc2865192013-07-10 14:46:23 -0700469 private boolean isRunningLocked() {
470 return mVpnUsers != null;
471 }
472
473 private void addVpnUserLocked(int user) {
474 enforceControlPermission();
475
476 if (!isRunningLocked()) {
477 throw new IllegalStateException("VPN is not active");
478 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700479
480 final boolean forwardDns = (mConfig.dnsServers != null &&
481 mConfig.dnsServers.size() != 0);
482
Chad Brubakerc2865192013-07-10 14:46:23 -0700483 // add the user
Robert Greenwalt69887e82013-09-24 11:05:57 -0700484 mCallback.addUserForwarding(mInterface, user, forwardDns);
Chad Brubakerc2865192013-07-10 14:46:23 -0700485 mVpnUsers.put(user, true);
486
487 // show the notification
488 if (!mPackage.equals(VpnConfig.LEGACY_VPN)) {
489 // Load everything for the user's notification
490 PackageManager pm = mContext.getPackageManager();
491 ApplicationInfo app = null;
492 try {
493 app = AppGlobals.getPackageManager().getApplicationInfo(mPackage, 0, mUserId);
494 } catch (RemoteException e) {
495 throw new IllegalStateException("Invalid application");
496 }
497 String label = app.loadLabel(pm).toString();
498 // Load the icon and convert it into a bitmap.
499 Drawable icon = app.loadIcon(pm);
500 Bitmap bitmap = null;
501 if (icon.getIntrinsicWidth() > 0 && icon.getIntrinsicHeight() > 0) {
502 int width = mContext.getResources().getDimensionPixelSize(
503 android.R.dimen.notification_large_icon_width);
504 int height = mContext.getResources().getDimensionPixelSize(
505 android.R.dimen.notification_large_icon_height);
506 icon.setBounds(0, 0, width, height);
507 bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
508 Canvas c = new Canvas(bitmap);
509 icon.draw(c);
510 c.setBitmap(null);
511 }
512 showNotification(label, bitmap, user);
513 } else {
514 showNotification(null, null, user);
515 }
516 }
517
518 private void removeVpnUserLocked(int user) {
519 enforceControlPermission();
520
521 if (!isRunningLocked()) {
522 throw new IllegalStateException("VPN is not active");
523 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700524 final boolean forwardDns = (mConfig.dnsServers != null &&
525 mConfig.dnsServers.size() != 0);
526 mCallback.clearUserForwarding(mInterface, user, forwardDns);
Chad Brubakerc2865192013-07-10 14:46:23 -0700527 mVpnUsers.delete(user);
528 hideNotification(user);
529 }
530
531 private void onUserAdded(int userId) {
532 // If the user is restricted tie them to the owner's VPN
533 synchronized(Vpn.this) {
534 UserManager mgr = UserManager.get(mContext);
535 UserInfo user = mgr.getUserInfo(userId);
536 if (user.isRestricted()) {
537 try {
538 addVpnUserLocked(userId);
539 } catch (Exception e) {
540 Log.wtf(TAG, "Failed to add restricted user to owner", e);
541 }
542 }
543 }
544 }
545
546 private void onUserRemoved(int userId) {
547 // clean up if restricted
548 synchronized(Vpn.this) {
549 UserManager mgr = UserManager.get(mContext);
550 UserInfo user = mgr.getUserInfo(userId);
551 if (user.isRestricted()) {
552 try {
553 removeVpnUserLocked(userId);
554 } catch (Exception e) {
555 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
556 }
557 }
558 }
559 }
560
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700561 /**
562 * Return the configuration of the currently running VPN.
563 */
564 public VpnConfig getVpnConfig() {
565 enforceControlPermission();
566 return mConfig;
567 }
568
Jeff Sharkey899223b2012-08-04 15:24:58 -0700569 @Deprecated
570 public synchronized void interfaceStatusChanged(String iface, boolean up) {
571 try {
572 mObserver.interfaceStatusChanged(iface, up);
573 } catch (RemoteException e) {
574 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700575 }
576 }
577
Jeff Sharkey899223b2012-08-04 15:24:58 -0700578 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
579 @Override
580 public void interfaceStatusChanged(String interfaze, boolean up) {
581 synchronized (Vpn.this) {
582 if (!up && mLegacyVpnRunner != null) {
583 mLegacyVpnRunner.check(interfaze);
584 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700585 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700586 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700587
Jeff Sharkey899223b2012-08-04 15:24:58 -0700588 @Override
589 public void interfaceRemoved(String interfaze) {
590 synchronized (Vpn.this) {
591 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
592 final long token = Binder.clearCallingIdentity();
593 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700594 final int size = mVpnUsers.size();
Robert Greenwalt69887e82013-09-24 11:05:57 -0700595 final boolean forwardDns = (mConfig.dnsServers != null &&
596 mConfig.dnsServers.size() != 0);
Chad Brubakerc2865192013-07-10 14:46:23 -0700597 for (int i = 0; i < size; i++) {
598 int user = mVpnUsers.keyAt(i);
Robert Greenwalt69887e82013-09-24 11:05:57 -0700599 mCallback.clearUserForwarding(mInterface, user, forwardDns);
Chad Brubakerc2865192013-07-10 14:46:23 -0700600 hideNotification(user);
601 }
602 mVpnUsers = null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700603 mCallback.clearMarkedForwarding(mInterface);
604
Jeff Sharkey899223b2012-08-04 15:24:58 -0700605 mCallback.restore();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700606 } finally {
607 Binder.restoreCallingIdentity(token);
608 }
609 mInterface = null;
610 if (mConnection != null) {
611 mContext.unbindService(mConnection);
612 mConnection = null;
613 updateState(DetailedState.DISCONNECTED, "interfaceRemoved");
614 } else if (mLegacyVpnRunner != null) {
615 mLegacyVpnRunner.exit();
616 mLegacyVpnRunner = null;
617 }
618 }
619 }
620 }
621 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700622
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700623 private void enforceControlPermission() {
624 // System user is allowed to control VPN.
625 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
626 return;
627 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700628 int appId = UserHandle.getAppId(Binder.getCallingUid());
629 final long token = Binder.clearCallingIdentity();
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700630 try {
Nick Kralevich212a1952013-10-18 17:48:39 -0700631 // System VPN dialogs are also allowed to control VPN.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700632 PackageManager pm = mContext.getPackageManager();
633 ApplicationInfo app = pm.getApplicationInfo(VpnConfig.DIALOGS_PACKAGE, 0);
Nick Kralevich212a1952013-10-18 17:48:39 -0700634 if (((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) && (appId == app.uid)) {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700635 return;
636 }
637 } catch (Exception e) {
638 // ignore
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700639 } finally {
640 Binder.restoreCallingIdentity(token);
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700641 }
642
643 throw new SecurityException("Unauthorized Caller");
644 }
645
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700646 private class Connection implements ServiceConnection {
647 private IBinder mService;
648
649 @Override
650 public void onServiceConnected(ComponentName name, IBinder service) {
651 mService = service;
652 }
653
654 @Override
655 public void onServiceDisconnected(ComponentName name) {
656 mService = null;
657 }
658 }
659
Chad Brubakerc2865192013-07-10 14:46:23 -0700660 private void showNotification(String label, Bitmap icon, int user) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700661 if (!mEnableNotif) return;
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700662 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700663
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700664 NotificationManager nm = (NotificationManager)
665 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
666
667 if (nm != null) {
Chia-chi Yeha4b87b52011-06-30 23:21:55 -0700668 String title = (label == null) ? mContext.getString(R.string.vpn_title) :
669 mContext.getString(R.string.vpn_title_long, label);
Chad Brubakerc2865192013-07-10 14:46:23 -0700670 String text = (mConfig.session == null) ? mContext.getString(R.string.vpn_text) :
671 mContext.getString(R.string.vpn_text_long, mConfig.session);
Chia-chi Yeha4b87b52011-06-30 23:21:55 -0700672
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700673 Notification notification = new Notification.Builder(mContext)
674 .setSmallIcon(R.drawable.vpn_connected)
Chia-chi Yeha4b87b52011-06-30 23:21:55 -0700675 .setLargeIcon(icon)
676 .setContentTitle(title)
Chia-chi Yehf8905fd2011-06-14 16:35:02 -0700677 .setContentText(text)
Jeff Sharkey899223b2012-08-04 15:24:58 -0700678 .setContentIntent(mStatusIntent)
Chia-chi Yeh50fe7092012-01-11 14:26:24 -0800679 .setDefaults(0)
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700680 .setOngoing(true)
Jeff Sharkey899223b2012-08-04 15:24:58 -0700681 .build();
Chad Brubakerc2865192013-07-10 14:46:23 -0700682 nm.notifyAsUser(null, R.drawable.vpn_connected, notification, new UserHandle(user));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700683 }
684 }
685
Chad Brubakerc2865192013-07-10 14:46:23 -0700686 private void hideNotification(int user) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700687 if (!mEnableNotif) return;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700688 mStatusIntent = null;
689
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700690 NotificationManager nm = (NotificationManager)
691 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
692
693 if (nm != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700694 nm.cancelAsUser(null, R.drawable.vpn_connected, new UserHandle(user));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700695 }
696 }
697
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700698 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700699 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700700 private native int jniSetAddresses(String interfaze, String addresses);
701 private native int jniSetRoutes(String interfaze, String routes);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700702 private native void jniReset(String interfaze);
703 private native int jniCheck(String interfaze);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700704
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900705 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
706 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700707 // Currently legacy VPN only works on IPv4.
708 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900709 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700710 }
711 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700712
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900713 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700714 }
715
716 /**
717 * Start legacy VPN, controlling native daemons as needed. Creates a
718 * secondary thread to perform connection work, returning quickly.
719 */
720 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800721 enforceControlPermission();
Kenny Rootb9594ce2013-02-14 10:18:38 -0800722 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700723 throw new IllegalStateException("KeyStore isn't unlocked");
724 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400725 UserManager mgr = UserManager.get(mContext);
726 UserInfo user = mgr.getUserInfo(mUserId);
727 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
728 throw new SecurityException("Restricted users cannot establish VPNs");
729 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700730
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900731 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
732 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
733 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700734
735 // Load certificates.
736 String privateKey = "";
737 String userCert = "";
738 String caCert = "";
739 String serverCert = "";
740 if (!profile.ipsecUserCert.isEmpty()) {
741 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
742 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700743 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700744 }
745 if (!profile.ipsecCaCert.isEmpty()) {
746 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700747 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700748 }
749 if (!profile.ipsecServerCert.isEmpty()) {
750 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700751 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700752 }
753 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
754 throw new IllegalStateException("Cannot load credentials");
755 }
756
757 // Prepare arguments for racoon.
758 String[] racoon = null;
759 switch (profile.type) {
760 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
761 racoon = new String[] {
762 iface, profile.server, "udppsk", profile.ipsecIdentifier,
763 profile.ipsecSecret, "1701",
764 };
765 break;
766 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
767 racoon = new String[] {
768 iface, profile.server, "udprsa", privateKey, userCert,
769 caCert, serverCert, "1701",
770 };
771 break;
772 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
773 racoon = new String[] {
774 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
775 profile.ipsecSecret, profile.username, profile.password, "", gateway,
776 };
777 break;
778 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
779 racoon = new String[] {
780 iface, profile.server, "xauthrsa", privateKey, userCert,
781 caCert, serverCert, profile.username, profile.password, "", gateway,
782 };
783 break;
784 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
785 racoon = new String[] {
786 iface, profile.server, "hybridrsa",
787 caCert, serverCert, profile.username, profile.password, "", gateway,
788 };
789 break;
790 }
791
792 // Prepare arguments for mtpd.
793 String[] mtpd = null;
794 switch (profile.type) {
795 case VpnProfile.TYPE_PPTP:
796 mtpd = new String[] {
797 iface, "pptp", profile.server, "1723",
798 "name", profile.username, "password", profile.password,
799 "linkname", "vpn", "refuse-eap", "nodefaultroute",
800 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
801 (profile.mppe ? "+mppe" : "nomppe"),
802 };
803 break;
804 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
805 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
806 mtpd = new String[] {
807 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
808 "name", profile.username, "password", profile.password,
809 "linkname", "vpn", "refuse-eap", "nodefaultroute",
810 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
811 };
812 break;
813 }
814
815 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700816 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700817 config.user = profile.key;
818 config.interfaze = iface;
819 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700820
821 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700822 if (!profile.dnsServers.isEmpty()) {
823 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
824 }
825 if (!profile.searchDomains.isEmpty()) {
826 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
827 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700828 startLegacyVpn(config, racoon, mtpd);
829 }
830
831 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
832 stopLegacyVpn();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700833
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700834 // Prepare for the new request. This also checks the caller.
835 prepare(null, VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700836 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700837
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700838 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700839 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
840 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700841 }
842
Jeff Sharkey899223b2012-08-04 15:24:58 -0700843 public synchronized void stopLegacyVpn() {
844 if (mLegacyVpnRunner != null) {
845 mLegacyVpnRunner.exit();
846 mLegacyVpnRunner = null;
847
848 synchronized (LegacyVpnRunner.TAG) {
849 // wait for old thread to completely finish before spinning up
850 // new instance, otherwise state updates can be out of order.
851 }
852 }
853 }
854
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700855 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700856 * Return the information of the current ongoing legacy VPN.
857 */
858 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700859 // Check if the caller is authorized.
860 enforceControlPermission();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700861 if (mLegacyVpnRunner == null) return null;
862
863 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -0700864 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700865 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
866 if (mNetworkInfo.isConnected()) {
867 info.intent = mStatusIntent;
868 }
869 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700870 }
871
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700872 public VpnConfig getLegacyVpnConfig() {
873 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700874 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700875 } else {
876 return null;
877 }
878 }
879
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700880 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700881 * Bringing up a VPN connection takes time, and that is all this thread
882 * does. Here we have plenty of time. The only thing we need to take
883 * care of is responding to interruptions as soon as possible. Otherwise
884 * requests will be piled up. This can be done in a Handler as a state
885 * machine, but it is much easier to read in the current form.
886 */
887 private class LegacyVpnRunner extends Thread {
888 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700889
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700890 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700891 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700892 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700893 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700894 private final AtomicInteger mOuterConnection =
895 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700896
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700897 private long mTimer = -1;
898
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700899 /**
900 * Watch for the outer connection (passing in the constructor) going away.
901 */
902 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
903 @Override
904 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -0700905 if (!mEnableTeardown) return;
906
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700907 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
908 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
909 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
910 NetworkInfo info = (NetworkInfo)intent.getExtra(
911 ConnectivityManager.EXTRA_NETWORK_INFO);
912 if (info != null && !info.isConnectedOrConnecting()) {
913 try {
914 mObserver.interfaceStatusChanged(mOuterInterface, false);
915 } catch (RemoteException e) {}
916 }
917 }
918 }
919 }
920 };
921
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700922 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700923 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700924 mConfig = config;
925 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -0700926 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700927 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700928 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700929
930 // This is the interface which VPN is running on,
931 // mConfig.interfaze will change to point to OUR
932 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700933 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700934 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700935 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700936 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700937
938 try {
939 mOuterConnection.set(
940 mConnService.findConnectionTypeForIface(mOuterInterface));
941 } catch (Exception e) {
942 mOuterConnection.set(ConnectivityManager.TYPE_NONE);
943 }
944
945 IntentFilter filter = new IntentFilter();
946 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
947 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700948 }
949
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700950 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700951 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700952 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
953 exit();
954 }
955 }
956
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700957 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700958 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700959 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700960 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -0700961 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700962 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700963 updateState(DetailedState.DISCONNECTED, "exit");
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700964 try {
965 mContext.unregisterReceiver(mBroadcastReceiver);
966 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700967 }
968
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700969 @Override
970 public void run() {
971 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700972 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700973 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700974 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700975 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700976 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700977 }
978 }
979
980 private void checkpoint(boolean yield) throws InterruptedException {
981 long now = SystemClock.elapsedRealtime();
982 if (mTimer == -1) {
983 mTimer = now;
984 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -0700985 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700986 Thread.sleep(yield ? 200 : 1);
987 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700988 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700989 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700990 }
991 }
992
993 private void execute() {
994 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -0700995 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700996 try {
997 // Initialize the timer.
998 checkpoint(false);
999
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001000 // Wait for the daemons to stop.
1001 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001002 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001003 checkpoint(true);
1004 }
1005 }
1006
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001007 // Clear the previous state.
1008 File state = new File("/data/misc/vpn/state");
1009 state.delete();
1010 if (state.exists()) {
1011 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001012 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001013 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001014 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001015
Chia-chi Yehe9107902011-07-02 01:48:50 -07001016 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001017 boolean restart = false;
1018 for (String[] arguments : mArguments) {
1019 restart = restart || (arguments != null);
1020 }
1021 if (!restart) {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001022 updateState(DetailedState.DISCONNECTED, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001023 return;
1024 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001025 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001026
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001027 // Start the daemon with arguments.
1028 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001029 String[] arguments = mArguments[i];
1030 if (arguments == null) {
1031 continue;
1032 }
1033
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001034 // Start the daemon.
1035 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001036 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001037
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001038 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001039 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001040 checkpoint(true);
1041 }
1042
1043 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001044 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001045 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001046 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001047
1048 // Wait for the socket to connect.
1049 while (true) {
1050 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001051 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001052 break;
1053 } catch (Exception e) {
1054 // ignore
1055 }
1056 checkpoint(true);
1057 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001058 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001059
1060 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001061 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001062 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001063 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001064 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001065 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001066 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001067 out.write(bytes.length >> 8);
1068 out.write(bytes.length);
1069 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001070 checkpoint(false);
1071 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001072 out.write(0xFF);
1073 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001074 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001075
1076 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001077 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001078 while (true) {
1079 try {
1080 if (in.read() == -1) {
1081 break;
1082 }
1083 } catch (Exception e) {
1084 // ignore
1085 }
1086 checkpoint(true);
1087 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001088 }
1089
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001090 // Wait for the daemons to create the new state.
1091 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001092 // Check if a running daemon is dead.
1093 for (int i = 0; i < mDaemons.length; ++i) {
1094 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001095 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001096 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001097 }
1098 }
1099 checkpoint(true);
1100 }
1101
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001102 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001103 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001104 if (parameters.length != 6) {
1105 throw new IllegalStateException("Cannot parse the state");
1106 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001107
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001108 // Set the interface and the addresses in the config.
1109 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001110
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001111 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001112 // Set the routes if they are not set in the config.
1113 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001114 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001115 }
1116
1117 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001118 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001119 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001120 if (!dnsServers.isEmpty()) {
1121 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1122 }
1123 }
1124
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001125 // Set the search domains if they are not set in the config.
1126 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1127 String searchDomains = parameters[4].trim();
1128 if (!searchDomains.isEmpty()) {
1129 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1130 }
1131 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001132
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001133 // Set the routes.
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001134 long token = Binder.clearCallingIdentity();
1135 try {
1136 mCallback.setMarkedForwarding(mConfig.interfaze);
1137 mCallback.setRoutes(mConfig.interfaze, mConfig.routes);
1138 } finally {
1139 Binder.restoreCallingIdentity(token);
1140 }
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001141
1142 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001143 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001144 // Set the start time
1145 mConfig.startTime = SystemClock.elapsedRealtime();
1146
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001147 // Check if the thread is interrupted while we are waiting.
1148 checkpoint(false);
1149
Chia-chi Yehe9107902011-07-02 01:48:50 -07001150 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001151 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001152 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001153 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001154
1155 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001156 mInterface = mConfig.interfaze;
Chad Brubakerc2865192013-07-10 14:46:23 -07001157 mVpnUsers = new SparseBooleanArray();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001158
1159 token = Binder.clearCallingIdentity();
1160 try {
1161 mCallback.override(mInterface, mConfig.dnsServers, mConfig.searchDomains);
Chad Brubakerc2865192013-07-10 14:46:23 -07001162 addVpnUserLocked(mUserId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001163 } finally {
1164 Binder.restoreCallingIdentity(token);
1165 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001166
Chad Brubakerc2865192013-07-10 14:46:23 -07001167 // Assign all restircted users to this VPN
1168 // (Legacy VPNs are Owner only)
1169 UserManager mgr = UserManager.get(mContext);
1170 token = Binder.clearCallingIdentity();
1171 try {
1172 for (UserInfo user : mgr.getUsers()) {
1173 if (user.isRestricted()) {
1174 try {
1175 addVpnUserLocked(user.id);
1176 } catch (Exception e) {
1177 Log.wtf(TAG, "Failed to add user " + user.id
1178 + " to owner's VPN");
1179 }
1180 }
1181 }
1182 } finally {
1183 Binder.restoreCallingIdentity(token);
1184 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001185 Log.i(TAG, "Connected!");
Jeff Sharkey899223b2012-08-04 15:24:58 -07001186 updateState(DetailedState.CONNECTED, "execute");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001187 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001188 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001189 Log.i(TAG, "Aborting", e);
Chad Brubakerc2865192013-07-10 14:46:23 -07001190 // make sure the routing is cleared
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001191 try {
1192 mCallback.clearMarkedForwarding(mConfig.interfaze);
1193 } catch (Exception ignored) {
1194 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001195 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001196 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001197 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001198 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001199 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001200 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001201 }
1202 }
1203
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001204 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001205 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
1206 updateState(DetailedState.FAILED, "execute");
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001207 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001208 }
1209 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001210
1211 /**
1212 * Monitor the daemons we started, moving to disconnected state if the
1213 * underlying services fail.
1214 */
1215 private void monitorDaemons() {
1216 if (!mNetworkInfo.isConnected()) {
1217 return;
1218 }
1219
1220 try {
1221 while (true) {
1222 Thread.sleep(2000);
1223 for (int i = 0; i < mDaemons.length; i++) {
1224 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1225 return;
1226 }
1227 }
1228 }
1229 } catch (InterruptedException e) {
1230 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1231 } finally {
1232 for (String daemon : mDaemons) {
1233 SystemService.stop(daemon);
1234 }
1235
1236 updateState(DetailedState.DISCONNECTED, "babysit");
1237 }
1238 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001239 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001240}