blob: 8466860a58a1ba8ab12d9237d4be751f24d2b920 [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;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -070020import static android.system.OsConstants.AF_INET;
21import static android.system.OsConstants.AF_INET6;
Jeff Sharkey899223b2012-08-04 15:24:58 -070022
Chad Brubaker4ca19e82013-06-14 11:16:51 -070023import android.app.AppGlobals;
Jeff Davidson05542602014-08-11 14:07:27 -070024import android.app.AppOpsManager;
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;
Jeff Sharkey899223b2012-08-04 15:24:58 -070036import android.net.ConnectivityManager;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070037import android.net.IConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070038import android.net.INetworkManagementEventObserver;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070039import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070040import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070041import android.net.LocalSocket;
42import android.net.LocalSocketAddress;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040043import android.net.NetworkAgent;
44import android.net.NetworkCapabilities;
Jeff Sharkey899223b2012-08-04 15:24:58 -070045import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040046import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070047import android.net.NetworkMisc;
Jeff Sharkey82f85212012-08-24 11:17:25 -070048import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040049import android.net.UidRange;
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;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040054import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070055import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070056import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070057import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070058import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070059import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070060import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070061import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070062import android.os.UserManager;
Jeff Sharkey82f85212012-08-24 11:17:25 -070063import android.security.Credentials;
64import android.security.KeyStore;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070065import android.util.Log;
66
Chad Brubakerc2865192013-07-10 14:46:23 -070067import com.android.internal.annotations.GuardedBy;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070068import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070069import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -070070import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070071import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070072
Jeff Davidson05542602014-08-11 14:07:27 -070073import libcore.io.IoUtils;
74
Chia-chi Yeh97a61562011-07-14 15:05:05 -070075import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070076import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070077import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070078import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070079import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -070080import java.net.Inet6Address;
81import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070082import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040083import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070084import java.util.Arrays;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040085import java.util.List;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070086import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070087
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070088/**
89 * @hide
90 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040091public class Vpn {
92 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -070093 private static final String TAG = "Vpn";
94 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040095
Jeff Sharkey899223b2012-08-04 15:24:58 -070096 // TODO: create separate trackers for each unique VPN to support
97 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070098
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040099 private Context mContext;
100 private NetworkInfo mNetworkInfo;
101 private String mPackage;
102 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700103 private String mInterface;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700104 private boolean mAllowIPv4;
105 private boolean mAllowIPv6;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700106 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700107 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Sharkey57666932013-04-30 17:01:57 -0700108 private volatile boolean mEnableTeardown = true;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700109 private final IConnectivityManager mConnService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400110 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700111 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400112 private NetworkAgent mNetworkAgent;
113 private final Looper mLooper;
114 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700115
116 /* list of users using this VPN. */
117 @GuardedBy("this")
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400118 private List<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700119 private BroadcastReceiver mUserIntentReceiver = null;
120
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700121 private final int mUserId;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700122
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400123 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700124 IConnectivityManager connService, int userId) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700125 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400126 mNetd = netService;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700127 mConnService = connService;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700128 mUserId = userId;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400129 mLooper = looper;
130
131 mPackage = VpnConfig.LEGACY_VPN;
132 mOwnerUID = getAppUid(mPackage);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700133
134 try {
135 netService.registerObserver(mObserver);
136 } catch (RemoteException e) {
137 Log.wtf(TAG, "Problem registering observer", e);
138 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700139 if (userId == UserHandle.USER_OWNER) {
140 // Owner's VPN also needs to handle restricted users
141 mUserIntentReceiver = new BroadcastReceiver() {
142 @Override
143 public void onReceive(Context context, Intent intent) {
144 final String action = intent.getAction();
145 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
146 UserHandle.USER_NULL);
147 if (userId == UserHandle.USER_NULL) return;
148
149 if (Intent.ACTION_USER_ADDED.equals(action)) {
150 onUserAdded(userId);
151 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
152 onUserRemoved(userId);
153 }
154 }
155 };
156
157 IntentFilter intentFilter = new IntentFilter();
158 intentFilter.addAction(Intent.ACTION_USER_ADDED);
159 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
160 mContext.registerReceiverAsUser(
161 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
162 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400163
164 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
165 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
166 mNetworkCapabilities = new NetworkCapabilities();
167 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
168 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700169 }
170
Jeff Sharkey57666932013-04-30 17:01:57 -0700171 /**
Jeff Sharkey57666932013-04-30 17:01:57 -0700172 * Set if this object is responsible for watching for {@link NetworkInfo}
173 * teardown. When {@code false}, teardown is handled externally by someone
174 * else.
175 */
176 public void setEnableTeardown(boolean enableTeardown) {
177 mEnableTeardown = enableTeardown;
178 }
179
Jeff Sharkey899223b2012-08-04 15:24:58 -0700180 /**
181 * Update current state, dispaching event to listeners.
182 */
183 private void updateState(DetailedState detailedState, String reason) {
184 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
185 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400186 if (mNetworkAgent != null) {
187 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
188 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700189 }
190
191 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700192 * Prepare for a VPN application. This method is designed to solve
193 * race conditions. It first compares the current prepared package
194 * with {@code oldPackage}. If they are the same, the prepared
195 * package is revoked and replaced with {@code newPackage}. If
196 * {@code oldPackage} is {@code null}, the comparison is omitted.
197 * If {@code newPackage} is the same package or {@code null}, the
198 * revocation is omitted. This method returns {@code true} if the
199 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700200 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700201 * Legacy VPN is handled specially since it is not a real package.
202 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
203 * it can be revoked by itself.
204 *
205 * @param oldPackage The package name of the old VPN application.
206 * @param newPackage The package name of the new VPN application.
207 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700208 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700209 public synchronized boolean prepare(String oldPackage, String newPackage) {
210 // Return false if the package does not match.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700211 if (oldPackage != null && !oldPackage.equals(mPackage)) {
Jeff Davidson05542602014-08-11 14:07:27 -0700212 // The package doesn't match. If this VPN was not previously authorized, return false
213 // to force user authorization. Otherwise, revoke the VPN anyway.
214 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
215 long token = Binder.clearCallingIdentity();
216 try {
217 // This looks bizarre, but it is what ConfirmDialog in VpnDialogs is doing when
218 // the user clicks through to allow the VPN to consent. So we are emulating the
219 // action of the dialog without actually showing it.
220 prepare(null, oldPackage);
221 } finally {
222 Binder.restoreCallingIdentity(token);
223 }
224 return true;
225 }
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700226 return false;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700227 }
228
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700229 // Return true if we do not need to revoke.
230 if (newPackage == null ||
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700231 (newPackage.equals(mPackage) && !newPackage.equals(VpnConfig.LEGACY_VPN))) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700232 return true;
233 }
234
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700235 // Check if the caller is authorized.
236 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700237
Jeff Davidson05542602014-08-11 14:07:27 -0700238 // Reset the interface.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700239 if (mInterface != null) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400240 agentDisconnect();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700241 jniReset(mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700242 mInterface = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700243 mVpnUsers = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700244 }
245
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700246 // Revoke the connection or stop LegacyVpnRunner.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700247 if (mConnection != null) {
248 try {
249 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
250 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
251 } catch (Exception e) {
252 // ignore
253 }
254 mContext.unbindService(mConnection);
255 mConnection = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700256 } else if (mLegacyVpnRunner != null) {
257 mLegacyVpnRunner.exit();
258 mLegacyVpnRunner = null;
259 }
260
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400261 long token = Binder.clearCallingIdentity();
262 try {
263 mNetd.denyProtect(mOwnerUID);
264 } catch (Exception e) {
265 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
266 } finally {
267 Binder.restoreCallingIdentity(token);
268 }
269
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700270 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
271 mPackage = newPackage;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400272 mOwnerUID = getAppUid(newPackage);
273 token = Binder.clearCallingIdentity();
274 try {
275 mNetd.allowProtect(mOwnerUID);
276 } catch (Exception e) {
277 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
278 } finally {
279 Binder.restoreCallingIdentity(token);
280 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700281 mConfig = null;
Jeff Davidson05542602014-08-11 14:07:27 -0700282
Jeff Sharkey899223b2012-08-04 15:24:58 -0700283 updateState(DetailedState.IDLE, "prepare");
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700284 return true;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700285 }
286
Jeff Davidson05542602014-08-11 14:07:27 -0700287 /**
288 * Set whether the current package has the ability to launch VPNs without user intervention.
289 */
290 public void setPackageAuthorization(boolean authorized) {
291 // Check if the caller is authorized.
292 enforceControlPermission();
293
294 if (mPackage == null || VpnConfig.LEGACY_VPN.equals(mPackage)) {
295 return;
296 }
297
298 long token = Binder.clearCallingIdentity();
299 try {
300 AppOpsManager appOps =
301 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
302 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, mOwnerUID, mPackage,
303 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
304 } catch (Exception e) {
305 Log.wtf(TAG, "Failed to set app ops for package " + mPackage, e);
306 } finally {
307 Binder.restoreCallingIdentity(token);
308 }
309 }
310
311 private boolean isVpnUserPreConsented(String packageName) {
312 AppOpsManager appOps =
313 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
314
315 // Verify that the caller matches the given package and has permission to activate VPNs.
316 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
317 packageName) == AppOpsManager.MODE_ALLOWED;
318 }
319
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400320 private int getAppUid(String app) {
Jeff Davidson05542602014-08-11 14:07:27 -0700321 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400322 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700323 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400324 PackageManager pm = mContext.getPackageManager();
325 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700326 try {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400327 result = pm.getPackageUid(app, mUserId);
328 } catch (NameNotFoundException e) {
329 result = -1;
330 }
331 return result;
332 }
333
334 public NetworkInfo getNetworkInfo() {
335 return mNetworkInfo;
336 }
337
338 private void agentConnect() {
339 LinkProperties lp = new LinkProperties();
340 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700341
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400342 boolean hasDefaultRoute = false;
343 for (RouteInfo route : mConfig.routes) {
344 lp.addRoute(route);
345 if (route.isDefaultRoute()) hasDefaultRoute = true;
346 }
347 if (hasDefaultRoute) {
348 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
349 } else {
350 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
351 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700352
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400353 if (mConfig.dnsServers != null) {
354 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700355 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
356 lp.addDnsServer(address);
357 if (address instanceof Inet4Address) {
358 mAllowIPv4 = true;
359 } else {
360 mAllowIPv6 = true;
361 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400362 }
363 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700364
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400365 // Concatenate search domains into a string.
366 StringBuilder buffer = new StringBuilder();
367 if (mConfig.searchDomains != null) {
368 for (String domain : mConfig.searchDomains) {
369 buffer.append(domain).append(' ');
370 }
371 }
372 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700373
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400374 mNetworkInfo.setIsAvailable(true);
375 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700376
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700377 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700378 networkMisc.allowBypass = mConfig.allowBypass;
379
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400380 long token = Binder.clearCallingIdentity();
381 try {
382 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700383 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700384 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400385 public void unwanted() {
386 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700387 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400388 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700389 } finally {
390 Binder.restoreCallingIdentity(token);
391 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700392
393 if (!mAllowIPv4) {
394 mNetworkAgent.blockAddressFamily(AF_INET);
395 }
396 if (!mAllowIPv6) {
397 mNetworkAgent.blockAddressFamily(AF_INET6);
398 }
399
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400400 addVpnUserLocked(mUserId);
401 // If we are owner assign all Restricted Users to this VPN
402 if (mUserId == UserHandle.USER_OWNER) {
403 token = Binder.clearCallingIdentity();
404 List<UserInfo> users;
405 try {
406 users = UserManager.get(mContext).getUsers();
407 } finally {
408 Binder.restoreCallingIdentity(token);
409 }
410 for (UserInfo user : users) {
411 if (user.isRestricted()) {
412 addVpnUserLocked(user.id);
413 }
414 }
415 }
416 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
417 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700418
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400419 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
420 networkInfo.setIsAvailable(false);
421 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
422 if (networkAgent != null) {
423 networkAgent.sendNetworkInfo(networkInfo);
424 }
425 }
426
427 private void agentDisconnect(NetworkAgent networkAgent) {
428 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
429 agentDisconnect(networkInfo, networkAgent);
430 }
431
432 private void agentDisconnect() {
433 if (mNetworkInfo.isConnected()) {
434 agentDisconnect(mNetworkInfo, mNetworkAgent);
435 mNetworkAgent = null;
436 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700437 }
438
439 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700440 * Establish a VPN network and return the file descriptor of the VPN
441 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700442 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700443 *
444 * @param config The parameters to configure the network.
445 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700446 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700447 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700448 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700449 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400450 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700451 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700452 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700453 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700454 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
455 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700456 long token = Binder.clearCallingIdentity();
457 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700458 // Restricted users are not allowed to create VPNs, they are tied to Owner
459 UserInfo user = mgr.getUserInfo(mUserId);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400460 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700461 throw new SecurityException("Restricted users cannot establish VPNs");
462 }
463
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700464 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
465 null, 0, mUserId);
466 if (info == null) {
467 throw new SecurityException("Cannot find " + config.user);
468 }
469 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
470 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
471 }
472 } catch (RemoteException e) {
473 throw new SecurityException("Cannot find " + config.user);
474 } finally {
475 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700476 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700477
Chad Brubaker850eb672014-03-21 21:02:47 +0000478 // Save the old config in case we need to go back.
479 VpnConfig oldConfig = mConfig;
480 String oldInterface = mInterface;
481 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400482 NetworkAgent oldNetworkAgent = mNetworkAgent;
483 mNetworkAgent = null;
484 List<UidRange> oldUsers = mVpnUsers;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700485 boolean oldAllowIPv4 = mAllowIPv4;
486 boolean oldAllowIPv6 = mAllowIPv6;
Chad Brubaker850eb672014-03-21 21:02:47 +0000487
Chia-chi Yehe9107902011-07-02 01:48:50 -0700488 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700489 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700490 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700491 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700492 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700493
Chad Brubakerc2865192013-07-10 14:46:23 -0700494 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700495 StringBuilder builder = new StringBuilder();
496 for (LinkAddress address : config.addresses) {
497 builder.append(" " + address);
498 }
499 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700500 throw new IllegalArgumentException("At least one address must be specified");
501 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700502 Connection connection = new Connection();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700503 if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
504 new UserHandle(mUserId))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700505 throw new IllegalStateException("Cannot bind " + config.user);
506 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000507
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700508 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700509 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700510
511 // Fill more values.
512 config.user = mPackage;
513 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700514 config.startTime = SystemClock.elapsedRealtime();
515 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000516
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700517 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400518 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700519 mAllowIPv4 = mConfig.allowIPv4;
520 mAllowIPv6 = mConfig.allowIPv6;
521
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400522 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000523
524 if (oldConnection != null) {
525 mContext.unbindService(oldConnection);
526 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400527 // Remove the old tun's user forwarding rules
528 // The new tun's user rules have already been added so they will take over
529 // as rules are deleted. This prevents data leakage as the rules are moved over.
530 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000531 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000532 jniReset(oldInterface);
533 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700534
535 try {
536 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
537 } catch (IOException e) {
538 throw new IllegalStateException(
539 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
540 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000541 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000542 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400543 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000544 // restore old state
545 mConfig = oldConfig;
546 mConnection = oldConnection;
547 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400548 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000549 mInterface = oldInterface;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700550 mAllowIPv4 = oldAllowIPv4;
551 mAllowIPv6 = oldAllowIPv6;
Chad Brubaker850eb672014-03-21 21:02:47 +0000552 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700553 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000554 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700555 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700556 }
557
Chad Brubakerc2865192013-07-10 14:46:23 -0700558 private boolean isRunningLocked() {
559 return mVpnUsers != null;
560 }
561
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400562 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Chad Brubakerc2865192013-07-10 14:46:23 -0700563 private void addVpnUserLocked(int user) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700564 if (!isRunningLocked()) {
565 throw new IllegalStateException("VPN is not active");
566 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700567
Chad Brubakerc2865192013-07-10 14:46:23 -0700568 // add the user
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400569 mVpnUsers.add(UidRange.createForUser(user));
Chad Brubakerc2865192013-07-10 14:46:23 -0700570 }
571
572 private void removeVpnUserLocked(int user) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700573 if (!isRunningLocked()) {
574 throw new IllegalStateException("VPN is not active");
575 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400576 UidRange uidRange = UidRange.createForUser(user);
577 if (mNetworkAgent != null) {
578 mNetworkAgent.removeUidRanges(new UidRange[] { uidRange });
579 }
580 mVpnUsers.remove(uidRange);
Chad Brubakerc2865192013-07-10 14:46:23 -0700581 }
582
583 private void onUserAdded(int userId) {
584 // If the user is restricted tie them to the owner's VPN
585 synchronized(Vpn.this) {
586 UserManager mgr = UserManager.get(mContext);
587 UserInfo user = mgr.getUserInfo(userId);
588 if (user.isRestricted()) {
589 try {
590 addVpnUserLocked(userId);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400591 if (mNetworkAgent != null) {
592 UidRange uidRange = UidRange.createForUser(userId);
593 mNetworkAgent.addUidRanges(new UidRange[] { uidRange });
594 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700595 } catch (Exception e) {
596 Log.wtf(TAG, "Failed to add restricted user to owner", e);
597 }
598 }
599 }
600 }
601
602 private void onUserRemoved(int userId) {
603 // clean up if restricted
604 synchronized(Vpn.this) {
605 UserManager mgr = UserManager.get(mContext);
606 UserInfo user = mgr.getUserInfo(userId);
607 if (user.isRestricted()) {
608 try {
609 removeVpnUserLocked(userId);
610 } catch (Exception e) {
611 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
612 }
613 }
614 }
615 }
616
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700617 /**
618 * Return the configuration of the currently running VPN.
619 */
620 public VpnConfig getVpnConfig() {
621 enforceControlPermission();
622 return mConfig;
623 }
624
Jeff Sharkey899223b2012-08-04 15:24:58 -0700625 @Deprecated
626 public synchronized void interfaceStatusChanged(String iface, boolean up) {
627 try {
628 mObserver.interfaceStatusChanged(iface, up);
629 } catch (RemoteException e) {
630 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700631 }
632 }
633
Jeff Sharkey899223b2012-08-04 15:24:58 -0700634 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
635 @Override
636 public void interfaceStatusChanged(String interfaze, boolean up) {
637 synchronized (Vpn.this) {
638 if (!up && mLegacyVpnRunner != null) {
639 mLegacyVpnRunner.check(interfaze);
640 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700641 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700642 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700643
Jeff Sharkey899223b2012-08-04 15:24:58 -0700644 @Override
645 public void interfaceRemoved(String interfaze) {
646 synchronized (Vpn.this) {
647 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400648 mVpnUsers = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700649 mInterface = null;
650 if (mConnection != null) {
651 mContext.unbindService(mConnection);
652 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400653 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700654 } else if (mLegacyVpnRunner != null) {
655 mLegacyVpnRunner.exit();
656 mLegacyVpnRunner = null;
657 }
658 }
659 }
660 }
661 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700662
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700663 private void enforceControlPermission() {
664 // System user is allowed to control VPN.
665 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
666 return;
667 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700668 int appId = UserHandle.getAppId(Binder.getCallingUid());
669 final long token = Binder.clearCallingIdentity();
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700670 try {
Nick Kralevich212a1952013-10-18 17:48:39 -0700671 // System VPN dialogs are also allowed to control VPN.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700672 PackageManager pm = mContext.getPackageManager();
673 ApplicationInfo app = pm.getApplicationInfo(VpnConfig.DIALOGS_PACKAGE, 0);
Nick Kralevich212a1952013-10-18 17:48:39 -0700674 if (((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) && (appId == app.uid)) {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700675 return;
676 }
Jason Monke47df842014-07-30 16:41:52 -0400677 // SystemUI dialogs are also allowed to control VPN.
678 ApplicationInfo sysUiApp = pm.getApplicationInfo("com.android.systemui", 0);
679 if (((sysUiApp.flags & ApplicationInfo.FLAG_SYSTEM) != 0) && (appId == sysUiApp.uid)) {
680 return;
681 }
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700682 } catch (Exception e) {
683 // ignore
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700684 } finally {
685 Binder.restoreCallingIdentity(token);
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700686 }
687
688 throw new SecurityException("Unauthorized Caller");
689 }
690
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700691 private class Connection implements ServiceConnection {
692 private IBinder mService;
693
694 @Override
695 public void onServiceConnected(ComponentName name, IBinder service) {
696 mService = service;
697 }
698
699 @Override
700 public void onServiceDisconnected(ComponentName name) {
701 mService = null;
702 }
703 }
704
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700705 public synchronized boolean addAddress(String address, int prefixLength) {
706 if (Binder.getCallingUid() != mOwnerUID || mInterface == null || mNetworkAgent == null) {
707 return false;
708 }
709 boolean success = jniAddAddress(mInterface, address, prefixLength);
710 if (success && (!mAllowIPv4 || !mAllowIPv6)) {
711 try {
712 InetAddress inetAddress = InetAddress.parseNumericAddress(address);
713 if ((inetAddress instanceof Inet4Address) && !mAllowIPv4) {
714 mAllowIPv4 = true;
715 mNetworkAgent.unblockAddressFamily(AF_INET);
716 } else if ((inetAddress instanceof Inet6Address) && !mAllowIPv6) {
717 mAllowIPv6 = true;
718 mNetworkAgent.unblockAddressFamily(AF_INET6);
719 }
720 } catch (IllegalArgumentException e) {
721 // ignore
722 }
723 }
724 // Ideally, we'd call mNetworkAgent.sendLinkProperties() here to notify ConnectivityService
725 // that the LinkAddress has changed. But we don't do so for two reasons: (1) We don't set
726 // LinkAddresses on the LinkProperties we establish in the first place (see agentConnect())
727 // and (2) CS doesn't do anything with LinkAddresses anyway (see updateLinkProperties()).
728 // TODO: Maybe fix this.
729 return success;
730 }
731
732 public synchronized boolean removeAddress(String address, int prefixLength) {
733 if (Binder.getCallingUid() != mOwnerUID || mInterface == null || mNetworkAgent == null) {
734 return false;
735 }
736 boolean success = jniDelAddress(mInterface, address, prefixLength);
737 // Ideally, we'd call mNetworkAgent.sendLinkProperties() here to notify ConnectivityService
738 // that the LinkAddress has changed. But we don't do so for two reasons: (1) We don't set
739 // LinkAddresses on the LinkProperties we establish in the first place (see agentConnect())
740 // and (2) CS doesn't do anything with LinkAddresses anyway (see updateLinkProperties()).
741 // TODO: Maybe fix this.
742 return success;
743 }
744
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700745 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700746 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700747 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700748 private native void jniReset(String interfaze);
749 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700750 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
751 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700752
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900753 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
754 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700755 // Currently legacy VPN only works on IPv4.
756 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900757 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700758 }
759 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700760
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900761 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700762 }
763
764 /**
765 * Start legacy VPN, controlling native daemons as needed. Creates a
766 * secondary thread to perform connection work, returning quickly.
767 */
768 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800769 enforceControlPermission();
Kenny Rootb9594ce2013-02-14 10:18:38 -0800770 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700771 throw new IllegalStateException("KeyStore isn't unlocked");
772 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400773 UserManager mgr = UserManager.get(mContext);
774 UserInfo user = mgr.getUserInfo(mUserId);
775 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
776 throw new SecurityException("Restricted users cannot establish VPNs");
777 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700778
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900779 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
780 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
781 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700782
783 // Load certificates.
784 String privateKey = "";
785 String userCert = "";
786 String caCert = "";
787 String serverCert = "";
788 if (!profile.ipsecUserCert.isEmpty()) {
789 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
790 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700791 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700792 }
793 if (!profile.ipsecCaCert.isEmpty()) {
794 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700795 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700796 }
797 if (!profile.ipsecServerCert.isEmpty()) {
798 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700799 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700800 }
801 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
802 throw new IllegalStateException("Cannot load credentials");
803 }
804
805 // Prepare arguments for racoon.
806 String[] racoon = null;
807 switch (profile.type) {
808 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
809 racoon = new String[] {
810 iface, profile.server, "udppsk", profile.ipsecIdentifier,
811 profile.ipsecSecret, "1701",
812 };
813 break;
814 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
815 racoon = new String[] {
816 iface, profile.server, "udprsa", privateKey, userCert,
817 caCert, serverCert, "1701",
818 };
819 break;
820 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
821 racoon = new String[] {
822 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
823 profile.ipsecSecret, profile.username, profile.password, "", gateway,
824 };
825 break;
826 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
827 racoon = new String[] {
828 iface, profile.server, "xauthrsa", privateKey, userCert,
829 caCert, serverCert, profile.username, profile.password, "", gateway,
830 };
831 break;
832 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
833 racoon = new String[] {
834 iface, profile.server, "hybridrsa",
835 caCert, serverCert, profile.username, profile.password, "", gateway,
836 };
837 break;
838 }
839
840 // Prepare arguments for mtpd.
841 String[] mtpd = null;
842 switch (profile.type) {
843 case VpnProfile.TYPE_PPTP:
844 mtpd = new String[] {
845 iface, "pptp", profile.server, "1723",
846 "name", profile.username, "password", profile.password,
847 "linkname", "vpn", "refuse-eap", "nodefaultroute",
848 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
849 (profile.mppe ? "+mppe" : "nomppe"),
850 };
851 break;
852 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
853 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
854 mtpd = new String[] {
855 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
856 "name", profile.username, "password", profile.password,
857 "linkname", "vpn", "refuse-eap", "nodefaultroute",
858 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
859 };
860 break;
861 }
862
863 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700864 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700865 config.user = profile.key;
866 config.interfaze = iface;
867 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700868
869 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700870 if (!profile.dnsServers.isEmpty()) {
871 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
872 }
873 if (!profile.searchDomains.isEmpty()) {
874 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
875 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700876 startLegacyVpn(config, racoon, mtpd);
877 }
878
879 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
880 stopLegacyVpn();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700881
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700882 // Prepare for the new request. This also checks the caller.
883 prepare(null, VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700884 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700885
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700886 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700887 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
888 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700889 }
890
Jeff Sharkey899223b2012-08-04 15:24:58 -0700891 public synchronized void stopLegacyVpn() {
892 if (mLegacyVpnRunner != null) {
893 mLegacyVpnRunner.exit();
894 mLegacyVpnRunner = null;
895
896 synchronized (LegacyVpnRunner.TAG) {
897 // wait for old thread to completely finish before spinning up
898 // new instance, otherwise state updates can be out of order.
899 }
900 }
901 }
902
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700903 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700904 * Return the information of the current ongoing legacy VPN.
905 */
906 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700907 // Check if the caller is authorized.
908 enforceControlPermission();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700909 if (mLegacyVpnRunner == null) return null;
910
911 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -0700912 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700913 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700914 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700915 }
916
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700917 public VpnConfig getLegacyVpnConfig() {
918 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700919 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700920 } else {
921 return null;
922 }
923 }
924
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700925 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700926 * Bringing up a VPN connection takes time, and that is all this thread
927 * does. Here we have plenty of time. The only thing we need to take
928 * care of is responding to interruptions as soon as possible. Otherwise
929 * requests will be piled up. This can be done in a Handler as a state
930 * machine, but it is much easier to read in the current form.
931 */
932 private class LegacyVpnRunner extends Thread {
933 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700934
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700935 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700936 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700937 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700938 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700939 private final AtomicInteger mOuterConnection =
940 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700941
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700942 private long mTimer = -1;
943
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700944 /**
945 * Watch for the outer connection (passing in the constructor) going away.
946 */
947 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
948 @Override
949 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -0700950 if (!mEnableTeardown) return;
951
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700952 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
953 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
954 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
955 NetworkInfo info = (NetworkInfo)intent.getExtra(
956 ConnectivityManager.EXTRA_NETWORK_INFO);
957 if (info != null && !info.isConnectedOrConnecting()) {
958 try {
959 mObserver.interfaceStatusChanged(mOuterInterface, false);
960 } catch (RemoteException e) {}
961 }
962 }
963 }
964 }
965 };
966
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700967 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700968 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700969 mConfig = config;
970 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -0700971 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700972 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700973 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700974
975 // This is the interface which VPN is running on,
976 // mConfig.interfaze will change to point to OUR
977 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700978 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700979 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700980 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700981 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700982
983 try {
984 mOuterConnection.set(
985 mConnService.findConnectionTypeForIface(mOuterInterface));
986 } catch (Exception e) {
987 mOuterConnection.set(ConnectivityManager.TYPE_NONE);
988 }
989
990 IntentFilter filter = new IntentFilter();
991 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
992 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700993 }
994
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700995 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700996 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700997 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
998 exit();
999 }
1000 }
1001
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001002 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001003 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001004 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001005 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001006 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001007 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001008 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001009 try {
1010 mContext.unregisterReceiver(mBroadcastReceiver);
1011 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001012 }
1013
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001014 @Override
1015 public void run() {
1016 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001017 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001018 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001019 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001020 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001021 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001022 }
1023 }
1024
1025 private void checkpoint(boolean yield) throws InterruptedException {
1026 long now = SystemClock.elapsedRealtime();
1027 if (mTimer == -1) {
1028 mTimer = now;
1029 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001030 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001031 Thread.sleep(yield ? 200 : 1);
1032 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001033 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001034 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001035 }
1036 }
1037
1038 private void execute() {
1039 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001040 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001041 try {
1042 // Initialize the timer.
1043 checkpoint(false);
1044
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001045 // Wait for the daemons to stop.
1046 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001047 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001048 checkpoint(true);
1049 }
1050 }
1051
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001052 // Clear the previous state.
1053 File state = new File("/data/misc/vpn/state");
1054 state.delete();
1055 if (state.exists()) {
1056 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001057 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001058 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001059 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001060
Chia-chi Yehe9107902011-07-02 01:48:50 -07001061 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001062 boolean restart = false;
1063 for (String[] arguments : mArguments) {
1064 restart = restart || (arguments != null);
1065 }
1066 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001067 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001068 return;
1069 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001070 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001071
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001072 // Start the daemon with arguments.
1073 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001074 String[] arguments = mArguments[i];
1075 if (arguments == null) {
1076 continue;
1077 }
1078
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001079 // Start the daemon.
1080 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001081 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001082
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001083 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001084 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001085 checkpoint(true);
1086 }
1087
1088 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001089 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001090 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001091 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001092
1093 // Wait for the socket to connect.
1094 while (true) {
1095 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001096 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001097 break;
1098 } catch (Exception e) {
1099 // ignore
1100 }
1101 checkpoint(true);
1102 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001103 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001104
1105 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001106 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001107 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001108 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001109 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001110 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001111 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001112 out.write(bytes.length >> 8);
1113 out.write(bytes.length);
1114 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001115 checkpoint(false);
1116 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001117 out.write(0xFF);
1118 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001119 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001120
1121 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001122 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001123 while (true) {
1124 try {
1125 if (in.read() == -1) {
1126 break;
1127 }
1128 } catch (Exception e) {
1129 // ignore
1130 }
1131 checkpoint(true);
1132 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001133 }
1134
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001135 // Wait for the daemons to create the new state.
1136 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001137 // Check if a running daemon is dead.
1138 for (int i = 0; i < mDaemons.length; ++i) {
1139 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001140 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001141 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001142 }
1143 }
1144 checkpoint(true);
1145 }
1146
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001147 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001148 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001149 if (parameters.length != 6) {
1150 throw new IllegalStateException("Cannot parse the state");
1151 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001152
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001153 // Set the interface and the addresses in the config.
1154 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001155
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001156 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001157 // Set the routes if they are not set in the config.
1158 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001159 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001160 }
1161
1162 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001163 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001164 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001165 if (!dnsServers.isEmpty()) {
1166 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1167 }
1168 }
1169
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001170 // Set the search domains if they are not set in the config.
1171 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1172 String searchDomains = parameters[4].trim();
1173 if (!searchDomains.isEmpty()) {
1174 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1175 }
1176 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001177
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001178 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001179 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001180 // Set the start time
1181 mConfig.startTime = SystemClock.elapsedRealtime();
1182
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001183 // Check if the thread is interrupted while we are waiting.
1184 checkpoint(false);
1185
Chia-chi Yehe9107902011-07-02 01:48:50 -07001186 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001187 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001188 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001189 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001190
1191 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001192 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001193 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001194 mAllowIPv4 = mConfig.allowIPv4;
1195 mAllowIPv6 = mConfig.allowIPv6;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001196
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001197 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001198
1199 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001200 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001201 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001202 Log.i(TAG, "Aborting", e);
Chia-chi Yehe9107902011-07-02 01:48:50 -07001203 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001204 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001205 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001206 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001207 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001208 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001209 }
1210 }
1211
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001212 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001213 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001214 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001215 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001216 }
1217 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001218
1219 /**
1220 * Monitor the daemons we started, moving to disconnected state if the
1221 * underlying services fail.
1222 */
1223 private void monitorDaemons() {
1224 if (!mNetworkInfo.isConnected()) {
1225 return;
1226 }
1227
1228 try {
1229 while (true) {
1230 Thread.sleep(2000);
1231 for (int i = 0; i < mDaemons.length; i++) {
1232 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1233 return;
1234 }
1235 }
1236 }
1237 } catch (InterruptedException e) {
1238 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1239 } finally {
1240 for (String daemon : mDaemons) {
1241 SystemService.stop(daemon);
1242 }
1243
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001244 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001245 }
1246 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001247 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001248}