blob: 94aa421dd1bf529d0b4d70b9a64dcb56341d31a8 [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;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -070025import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070026import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070027import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070028import android.content.Context;
29import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070030import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070031import android.content.ServiceConnection;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070032import android.content.pm.ApplicationInfo;
33import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040034import android.content.pm.PackageManager.NameNotFoundException;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070035import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070036import android.content.pm.UserInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070037import android.net.ConnectivityManager;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070038import android.net.IConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070039import android.net.INetworkManagementEventObserver;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070040import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070041import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070042import android.net.LocalSocket;
43import android.net.LocalSocketAddress;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040044import android.net.NetworkAgent;
45import android.net.NetworkCapabilities;
Jeff Sharkey899223b2012-08-04 15:24:58 -070046import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040047import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070048import android.net.NetworkMisc;
Jeff Sharkey82f85212012-08-24 11:17:25 -070049import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040050import android.net.UidRange;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070051import android.os.Binder;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080052import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070053import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070054import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040055import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070056import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070057import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070058import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070059import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070060import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070061import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070062import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070063import android.os.UserManager;
Jeff Sharkey82f85212012-08-24 11:17:25 -070064import android.security.Credentials;
65import android.security.KeyStore;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070066import android.util.Log;
67
Chad Brubakerc2865192013-07-10 14:46:23 -070068import com.android.internal.annotations.GuardedBy;
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;
Jeff Sharkey899223b2012-08-04 15:24:58 -070072import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070073
Jeff Davidson05542602014-08-11 14:07:27 -070074import libcore.io.IoUtils;
75
Chia-chi Yeh97a61562011-07-14 15:05:05 -070076import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070077import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070078import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070079import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070080import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -070081import java.net.Inet6Address;
82import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070083import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040084import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070085import java.util.Arrays;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040086import java.util.List;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070087import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070088
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070089/**
90 * @hide
91 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040092public class Vpn {
93 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -070094 private static final String TAG = "Vpn";
95 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040096
Jeff Sharkey899223b2012-08-04 15:24:58 -070097 // TODO: create separate trackers for each unique VPN to support
98 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070099
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400100 private Context mContext;
101 private NetworkInfo mNetworkInfo;
102 private String mPackage;
103 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700104 private String mInterface;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700105 private boolean mAllowIPv4;
106 private boolean mAllowIPv6;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700107 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700108 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700109 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700110 private volatile boolean mEnableTeardown = true;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700111 private final IConnectivityManager mConnService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400112 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700113 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400114 private NetworkAgent mNetworkAgent;
115 private final Looper mLooper;
116 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700117
118 /* list of users using this VPN. */
119 @GuardedBy("this")
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400120 private List<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700121 private BroadcastReceiver mUserIntentReceiver = null;
122
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700123 private final int mUserId;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700124
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400125 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700126 IConnectivityManager connService, int userId) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700127 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400128 mNetd = netService;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700129 mConnService = connService;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700130 mUserId = userId;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400131 mLooper = looper;
132
133 mPackage = VpnConfig.LEGACY_VPN;
134 mOwnerUID = getAppUid(mPackage);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700135
136 try {
137 netService.registerObserver(mObserver);
138 } catch (RemoteException e) {
139 Log.wtf(TAG, "Problem registering observer", e);
140 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700141 if (userId == UserHandle.USER_OWNER) {
142 // Owner's VPN also needs to handle restricted users
143 mUserIntentReceiver = new BroadcastReceiver() {
144 @Override
145 public void onReceive(Context context, Intent intent) {
146 final String action = intent.getAction();
147 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
148 UserHandle.USER_NULL);
149 if (userId == UserHandle.USER_NULL) return;
150
151 if (Intent.ACTION_USER_ADDED.equals(action)) {
152 onUserAdded(userId);
153 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
154 onUserRemoved(userId);
155 }
156 }
157 };
158
159 IntentFilter intentFilter = new IntentFilter();
160 intentFilter.addAction(Intent.ACTION_USER_ADDED);
161 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
162 mContext.registerReceiverAsUser(
163 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
164 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400165
166 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
167 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
168 mNetworkCapabilities = new NetworkCapabilities();
169 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
170 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700171 }
172
Jeff Sharkey57666932013-04-30 17:01:57 -0700173 /**
Jeff Sharkey57666932013-04-30 17:01:57 -0700174 * Set if this object is responsible for watching for {@link NetworkInfo}
175 * teardown. When {@code false}, teardown is handled externally by someone
176 * else.
177 */
178 public void setEnableTeardown(boolean enableTeardown) {
179 mEnableTeardown = enableTeardown;
180 }
181
Jeff Sharkey899223b2012-08-04 15:24:58 -0700182 /**
183 * Update current state, dispaching event to listeners.
184 */
185 private void updateState(DetailedState detailedState, String reason) {
186 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
187 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400188 if (mNetworkAgent != null) {
189 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
190 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700191 }
192
193 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700194 * Prepare for a VPN application. This method is designed to solve
195 * race conditions. It first compares the current prepared package
196 * with {@code oldPackage}. If they are the same, the prepared
197 * package is revoked and replaced with {@code newPackage}. If
198 * {@code oldPackage} is {@code null}, the comparison is omitted.
199 * If {@code newPackage} is the same package or {@code null}, the
200 * revocation is omitted. This method returns {@code true} if the
201 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700202 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700203 * Legacy VPN is handled specially since it is not a real package.
204 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
205 * it can be revoked by itself.
206 *
207 * @param oldPackage The package name of the old VPN application.
208 * @param newPackage The package name of the new VPN application.
209 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700210 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700211 public synchronized boolean prepare(String oldPackage, String newPackage) {
212 // Return false if the package does not match.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700213 if (oldPackage != null && !oldPackage.equals(mPackage)) {
Jeff Davidson05542602014-08-11 14:07:27 -0700214 // The package doesn't match. If this VPN was not previously authorized, return false
215 // to force user authorization. Otherwise, revoke the VPN anyway.
216 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
217 long token = Binder.clearCallingIdentity();
218 try {
219 // This looks bizarre, but it is what ConfirmDialog in VpnDialogs is doing when
220 // the user clicks through to allow the VPN to consent. So we are emulating the
221 // action of the dialog without actually showing it.
222 prepare(null, oldPackage);
223 } finally {
224 Binder.restoreCallingIdentity(token);
225 }
226 return true;
227 }
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700228 return false;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700229 }
230
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700231 // Return true if we do not need to revoke.
232 if (newPackage == null ||
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700233 (newPackage.equals(mPackage) && !newPackage.equals(VpnConfig.LEGACY_VPN))) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700234 return true;
235 }
236
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700237 // Check if the caller is authorized.
238 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700239
Jeff Davidson05542602014-08-11 14:07:27 -0700240 // Reset the interface.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700241 if (mInterface != null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700242 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400243 agentDisconnect();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700244 jniReset(mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700245 mInterface = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700246 mVpnUsers = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700247 }
248
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700249 // Revoke the connection or stop LegacyVpnRunner.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700250 if (mConnection != null) {
251 try {
252 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
253 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
254 } catch (Exception e) {
255 // ignore
256 }
257 mContext.unbindService(mConnection);
258 mConnection = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700259 } else if (mLegacyVpnRunner != null) {
260 mLegacyVpnRunner.exit();
261 mLegacyVpnRunner = null;
262 }
263
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400264 long token = Binder.clearCallingIdentity();
265 try {
266 mNetd.denyProtect(mOwnerUID);
267 } catch (Exception e) {
268 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
269 } finally {
270 Binder.restoreCallingIdentity(token);
271 }
272
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700273 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
274 mPackage = newPackage;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400275 mOwnerUID = getAppUid(newPackage);
276 token = Binder.clearCallingIdentity();
277 try {
278 mNetd.allowProtect(mOwnerUID);
279 } catch (Exception e) {
280 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
281 } finally {
282 Binder.restoreCallingIdentity(token);
283 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700284 mConfig = null;
Jeff Davidson05542602014-08-11 14:07:27 -0700285
Jeff Sharkey899223b2012-08-04 15:24:58 -0700286 updateState(DetailedState.IDLE, "prepare");
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700287 return true;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700288 }
289
Jeff Davidson05542602014-08-11 14:07:27 -0700290 /**
291 * Set whether the current package has the ability to launch VPNs without user intervention.
292 */
293 public void setPackageAuthorization(boolean authorized) {
294 // Check if the caller is authorized.
295 enforceControlPermission();
296
297 if (mPackage == null || VpnConfig.LEGACY_VPN.equals(mPackage)) {
298 return;
299 }
300
301 long token = Binder.clearCallingIdentity();
302 try {
303 AppOpsManager appOps =
304 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
305 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, mOwnerUID, mPackage,
306 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
307 } catch (Exception e) {
308 Log.wtf(TAG, "Failed to set app ops for package " + mPackage, e);
309 } finally {
310 Binder.restoreCallingIdentity(token);
311 }
312 }
313
314 private boolean isVpnUserPreConsented(String packageName) {
315 AppOpsManager appOps =
316 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
317
318 // Verify that the caller matches the given package and has permission to activate VPNs.
319 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
320 packageName) == AppOpsManager.MODE_ALLOWED;
321 }
322
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400323 private int getAppUid(String app) {
Jeff Davidson05542602014-08-11 14:07:27 -0700324 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400325 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700326 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400327 PackageManager pm = mContext.getPackageManager();
328 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700329 try {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400330 result = pm.getPackageUid(app, mUserId);
331 } catch (NameNotFoundException e) {
332 result = -1;
333 }
334 return result;
335 }
336
337 public NetworkInfo getNetworkInfo() {
338 return mNetworkInfo;
339 }
340
341 private void agentConnect() {
342 LinkProperties lp = new LinkProperties();
343 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700344
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400345 boolean hasDefaultRoute = false;
346 for (RouteInfo route : mConfig.routes) {
347 lp.addRoute(route);
348 if (route.isDefaultRoute()) hasDefaultRoute = true;
349 }
350 if (hasDefaultRoute) {
351 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
352 } else {
353 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
354 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700355
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400356 if (mConfig.dnsServers != null) {
357 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700358 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
359 lp.addDnsServer(address);
360 if (address instanceof Inet4Address) {
361 mAllowIPv4 = true;
362 } else {
363 mAllowIPv6 = true;
364 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400365 }
366 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700367
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400368 // Concatenate search domains into a string.
369 StringBuilder buffer = new StringBuilder();
370 if (mConfig.searchDomains != null) {
371 for (String domain : mConfig.searchDomains) {
372 buffer.append(domain).append(' ');
373 }
374 }
375 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700376
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400377 mNetworkInfo.setIsAvailable(true);
378 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700379
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700380 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700381 networkMisc.allowBypass = mConfig.allowBypass;
382
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400383 long token = Binder.clearCallingIdentity();
384 try {
385 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700386 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700387 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400388 public void unwanted() {
389 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700390 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400391 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700392 } finally {
393 Binder.restoreCallingIdentity(token);
394 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700395
396 if (!mAllowIPv4) {
397 mNetworkAgent.blockAddressFamily(AF_INET);
398 }
399 if (!mAllowIPv6) {
400 mNetworkAgent.blockAddressFamily(AF_INET6);
401 }
402
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400403 addVpnUserLocked(mUserId);
404 // If we are owner assign all Restricted Users to this VPN
405 if (mUserId == UserHandle.USER_OWNER) {
406 token = Binder.clearCallingIdentity();
407 List<UserInfo> users;
408 try {
409 users = UserManager.get(mContext).getUsers();
410 } finally {
411 Binder.restoreCallingIdentity(token);
412 }
413 for (UserInfo user : users) {
414 if (user.isRestricted()) {
415 addVpnUserLocked(user.id);
416 }
417 }
418 }
419 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
420 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700421
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400422 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
423 networkInfo.setIsAvailable(false);
424 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
425 if (networkAgent != null) {
426 networkAgent.sendNetworkInfo(networkInfo);
427 }
428 }
429
430 private void agentDisconnect(NetworkAgent networkAgent) {
431 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
432 agentDisconnect(networkInfo, networkAgent);
433 }
434
435 private void agentDisconnect() {
436 if (mNetworkInfo.isConnected()) {
437 agentDisconnect(mNetworkInfo, mNetworkAgent);
438 mNetworkAgent = null;
439 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700440 }
441
442 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700443 * Establish a VPN network and return the file descriptor of the VPN
444 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700445 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700446 *
447 * @param config The parameters to configure the network.
448 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700449 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700450 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700451 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700452 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400453 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700454 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700455 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700456 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700457 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
458 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700459 long token = Binder.clearCallingIdentity();
460 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700461 // Restricted users are not allowed to create VPNs, they are tied to Owner
462 UserInfo user = mgr.getUserInfo(mUserId);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400463 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700464 throw new SecurityException("Restricted users cannot establish VPNs");
465 }
466
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700467 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
468 null, 0, mUserId);
469 if (info == null) {
470 throw new SecurityException("Cannot find " + config.user);
471 }
472 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
473 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
474 }
475 } catch (RemoteException e) {
476 throw new SecurityException("Cannot find " + config.user);
477 } finally {
478 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700479 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700480
Chad Brubaker850eb672014-03-21 21:02:47 +0000481 // Save the old config in case we need to go back.
482 VpnConfig oldConfig = mConfig;
483 String oldInterface = mInterface;
484 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400485 NetworkAgent oldNetworkAgent = mNetworkAgent;
486 mNetworkAgent = null;
487 List<UidRange> oldUsers = mVpnUsers;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700488 boolean oldAllowIPv4 = mAllowIPv4;
489 boolean oldAllowIPv6 = mAllowIPv6;
Chad Brubaker850eb672014-03-21 21:02:47 +0000490
Chia-chi Yehe9107902011-07-02 01:48:50 -0700491 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700492 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700493 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700494 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700495 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700496
Chad Brubakerc2865192013-07-10 14:46:23 -0700497 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700498 StringBuilder builder = new StringBuilder();
499 for (LinkAddress address : config.addresses) {
500 builder.append(" " + address);
501 }
502 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700503 throw new IllegalArgumentException("At least one address must be specified");
504 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700505 Connection connection = new Connection();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700506 if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
507 new UserHandle(mUserId))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700508 throw new IllegalStateException("Cannot bind " + config.user);
509 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000510
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700511 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700512 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700513
514 // Fill more values.
515 config.user = mPackage;
516 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700517 config.startTime = SystemClock.elapsedRealtime();
518 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000519
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700520 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400521 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700522 mAllowIPv4 = mConfig.allowIPv4;
523 mAllowIPv6 = mConfig.allowIPv6;
524
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400525 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000526
527 if (oldConnection != null) {
528 mContext.unbindService(oldConnection);
529 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400530 // Remove the old tun's user forwarding rules
531 // The new tun's user rules have already been added so they will take over
532 // as rules are deleted. This prevents data leakage as the rules are moved over.
533 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000534 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000535 jniReset(oldInterface);
536 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700537
538 try {
539 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
540 } catch (IOException e) {
541 throw new IllegalStateException(
542 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
543 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000544 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000545 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400546 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000547 // restore old state
548 mConfig = oldConfig;
549 mConnection = oldConnection;
550 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400551 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000552 mInterface = oldInterface;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700553 mAllowIPv4 = oldAllowIPv4;
554 mAllowIPv6 = oldAllowIPv6;
Chad Brubaker850eb672014-03-21 21:02:47 +0000555 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700556 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000557 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700558 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700559 }
560
Chad Brubakerc2865192013-07-10 14:46:23 -0700561 private boolean isRunningLocked() {
562 return mVpnUsers != null;
563 }
564
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400565 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Chad Brubakerc2865192013-07-10 14:46:23 -0700566 private void addVpnUserLocked(int user) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700567 if (!isRunningLocked()) {
568 throw new IllegalStateException("VPN is not active");
569 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700570
Chad Brubakerc2865192013-07-10 14:46:23 -0700571 // add the user
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400572 mVpnUsers.add(UidRange.createForUser(user));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700573
574 prepareStatusIntent();
Chad Brubakerc2865192013-07-10 14:46:23 -0700575 }
576
577 private void removeVpnUserLocked(int user) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700578 if (!isRunningLocked()) {
579 throw new IllegalStateException("VPN is not active");
580 }
581 UidRange uidRange = UidRange.createForUser(user);
582 if (mNetworkAgent != null) {
583 mNetworkAgent.removeUidRanges(new UidRange[] { uidRange });
584 }
585 mVpnUsers.remove(uidRange);
586 mStatusIntent = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700587 }
588
589 private void onUserAdded(int userId) {
590 // If the user is restricted tie them to the owner's VPN
591 synchronized(Vpn.this) {
592 UserManager mgr = UserManager.get(mContext);
593 UserInfo user = mgr.getUserInfo(userId);
594 if (user.isRestricted()) {
595 try {
596 addVpnUserLocked(userId);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400597 if (mNetworkAgent != null) {
598 UidRange uidRange = UidRange.createForUser(userId);
599 mNetworkAgent.addUidRanges(new UidRange[] { uidRange });
600 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700601 } catch (Exception e) {
602 Log.wtf(TAG, "Failed to add restricted user to owner", e);
603 }
604 }
605 }
606 }
607
608 private void onUserRemoved(int userId) {
609 // clean up if restricted
610 synchronized(Vpn.this) {
611 UserManager mgr = UserManager.get(mContext);
612 UserInfo user = mgr.getUserInfo(userId);
613 if (user.isRestricted()) {
614 try {
615 removeVpnUserLocked(userId);
616 } catch (Exception e) {
617 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
618 }
619 }
620 }
621 }
622
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700623 /**
624 * Return the configuration of the currently running VPN.
625 */
626 public VpnConfig getVpnConfig() {
627 enforceControlPermission();
628 return mConfig;
629 }
630
Jeff Sharkey899223b2012-08-04 15:24:58 -0700631 @Deprecated
632 public synchronized void interfaceStatusChanged(String iface, boolean up) {
633 try {
634 mObserver.interfaceStatusChanged(iface, up);
635 } catch (RemoteException e) {
636 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700637 }
638 }
639
Jeff Sharkey899223b2012-08-04 15:24:58 -0700640 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
641 @Override
642 public void interfaceStatusChanged(String interfaze, boolean up) {
643 synchronized (Vpn.this) {
644 if (!up && mLegacyVpnRunner != null) {
645 mLegacyVpnRunner.check(interfaze);
646 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700647 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700648 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700649
Jeff Sharkey899223b2012-08-04 15:24:58 -0700650 @Override
651 public void interfaceRemoved(String interfaze) {
652 synchronized (Vpn.this) {
653 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700654 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400655 mVpnUsers = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700656 mInterface = null;
657 if (mConnection != null) {
658 mContext.unbindService(mConnection);
659 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400660 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700661 } else if (mLegacyVpnRunner != null) {
662 mLegacyVpnRunner.exit();
663 mLegacyVpnRunner = null;
664 }
665 }
666 }
667 }
668 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700669
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700670 private void enforceControlPermission() {
671 // System user is allowed to control VPN.
672 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
673 return;
674 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700675 int appId = UserHandle.getAppId(Binder.getCallingUid());
676 final long token = Binder.clearCallingIdentity();
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700677 try {
Nick Kralevich212a1952013-10-18 17:48:39 -0700678 // System VPN dialogs are also allowed to control VPN.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700679 PackageManager pm = mContext.getPackageManager();
680 ApplicationInfo app = pm.getApplicationInfo(VpnConfig.DIALOGS_PACKAGE, 0);
Nick Kralevich212a1952013-10-18 17:48:39 -0700681 if (((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) && (appId == app.uid)) {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700682 return;
683 }
Jason Monke47df842014-07-30 16:41:52 -0400684 // SystemUI dialogs are also allowed to control VPN.
685 ApplicationInfo sysUiApp = pm.getApplicationInfo("com.android.systemui", 0);
686 if (((sysUiApp.flags & ApplicationInfo.FLAG_SYSTEM) != 0) && (appId == sysUiApp.uid)) {
687 return;
688 }
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700689 } catch (Exception e) {
690 // ignore
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700691 } finally {
692 Binder.restoreCallingIdentity(token);
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700693 }
694
695 throw new SecurityException("Unauthorized Caller");
696 }
697
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700698 private class Connection implements ServiceConnection {
699 private IBinder mService;
700
701 @Override
702 public void onServiceConnected(ComponentName name, IBinder service) {
703 mService = service;
704 }
705
706 @Override
707 public void onServiceDisconnected(ComponentName name) {
708 mService = null;
709 }
710 }
711
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700712 private void prepareStatusIntent() {
713 final long token = Binder.clearCallingIdentity();
714 try {
715 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
716 } finally {
717 Binder.restoreCallingIdentity(token);
718 }
719 }
720
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700721 public synchronized boolean addAddress(String address, int prefixLength) {
722 if (Binder.getCallingUid() != mOwnerUID || mInterface == null || mNetworkAgent == null) {
723 return false;
724 }
725 boolean success = jniAddAddress(mInterface, address, prefixLength);
726 if (success && (!mAllowIPv4 || !mAllowIPv6)) {
727 try {
728 InetAddress inetAddress = InetAddress.parseNumericAddress(address);
729 if ((inetAddress instanceof Inet4Address) && !mAllowIPv4) {
730 mAllowIPv4 = true;
731 mNetworkAgent.unblockAddressFamily(AF_INET);
732 } else if ((inetAddress instanceof Inet6Address) && !mAllowIPv6) {
733 mAllowIPv6 = true;
734 mNetworkAgent.unblockAddressFamily(AF_INET6);
735 }
736 } catch (IllegalArgumentException e) {
737 // ignore
738 }
739 }
740 // Ideally, we'd call mNetworkAgent.sendLinkProperties() here to notify ConnectivityService
741 // that the LinkAddress has changed. But we don't do so for two reasons: (1) We don't set
742 // LinkAddresses on the LinkProperties we establish in the first place (see agentConnect())
743 // and (2) CS doesn't do anything with LinkAddresses anyway (see updateLinkProperties()).
744 // TODO: Maybe fix this.
745 return success;
746 }
747
748 public synchronized boolean removeAddress(String address, int prefixLength) {
749 if (Binder.getCallingUid() != mOwnerUID || mInterface == null || mNetworkAgent == null) {
750 return false;
751 }
752 boolean success = jniDelAddress(mInterface, address, prefixLength);
753 // Ideally, we'd call mNetworkAgent.sendLinkProperties() here to notify ConnectivityService
754 // that the LinkAddress has changed. But we don't do so for two reasons: (1) We don't set
755 // LinkAddresses on the LinkProperties we establish in the first place (see agentConnect())
756 // and (2) CS doesn't do anything with LinkAddresses anyway (see updateLinkProperties()).
757 // TODO: Maybe fix this.
758 return success;
759 }
760
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700761 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700762 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700763 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700764 private native void jniReset(String interfaze);
765 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700766 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
767 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700768
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900769 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
770 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700771 // Currently legacy VPN only works on IPv4.
772 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900773 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700774 }
775 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700776
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900777 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700778 }
779
780 /**
781 * Start legacy VPN, controlling native daemons as needed. Creates a
782 * secondary thread to perform connection work, returning quickly.
783 */
784 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800785 enforceControlPermission();
Kenny Rootb9594ce2013-02-14 10:18:38 -0800786 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700787 throw new IllegalStateException("KeyStore isn't unlocked");
788 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400789 UserManager mgr = UserManager.get(mContext);
790 UserInfo user = mgr.getUserInfo(mUserId);
791 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
792 throw new SecurityException("Restricted users cannot establish VPNs");
793 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700794
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900795 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
796 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
797 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700798
799 // Load certificates.
800 String privateKey = "";
801 String userCert = "";
802 String caCert = "";
803 String serverCert = "";
804 if (!profile.ipsecUserCert.isEmpty()) {
805 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
806 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700807 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700808 }
809 if (!profile.ipsecCaCert.isEmpty()) {
810 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700811 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700812 }
813 if (!profile.ipsecServerCert.isEmpty()) {
814 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700815 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700816 }
817 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
818 throw new IllegalStateException("Cannot load credentials");
819 }
820
821 // Prepare arguments for racoon.
822 String[] racoon = null;
823 switch (profile.type) {
824 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
825 racoon = new String[] {
826 iface, profile.server, "udppsk", profile.ipsecIdentifier,
827 profile.ipsecSecret, "1701",
828 };
829 break;
830 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
831 racoon = new String[] {
832 iface, profile.server, "udprsa", privateKey, userCert,
833 caCert, serverCert, "1701",
834 };
835 break;
836 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
837 racoon = new String[] {
838 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
839 profile.ipsecSecret, profile.username, profile.password, "", gateway,
840 };
841 break;
842 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
843 racoon = new String[] {
844 iface, profile.server, "xauthrsa", privateKey, userCert,
845 caCert, serverCert, profile.username, profile.password, "", gateway,
846 };
847 break;
848 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
849 racoon = new String[] {
850 iface, profile.server, "hybridrsa",
851 caCert, serverCert, profile.username, profile.password, "", gateway,
852 };
853 break;
854 }
855
856 // Prepare arguments for mtpd.
857 String[] mtpd = null;
858 switch (profile.type) {
859 case VpnProfile.TYPE_PPTP:
860 mtpd = new String[] {
861 iface, "pptp", profile.server, "1723",
862 "name", profile.username, "password", profile.password,
863 "linkname", "vpn", "refuse-eap", "nodefaultroute",
864 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
865 (profile.mppe ? "+mppe" : "nomppe"),
866 };
867 break;
868 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
869 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
870 mtpd = new String[] {
871 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
872 "name", profile.username, "password", profile.password,
873 "linkname", "vpn", "refuse-eap", "nodefaultroute",
874 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
875 };
876 break;
877 }
878
879 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700880 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700881 config.user = profile.key;
882 config.interfaze = iface;
883 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700884
885 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700886 if (!profile.dnsServers.isEmpty()) {
887 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
888 }
889 if (!profile.searchDomains.isEmpty()) {
890 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
891 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700892 startLegacyVpn(config, racoon, mtpd);
893 }
894
895 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
896 stopLegacyVpn();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700897
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700898 // Prepare for the new request. This also checks the caller.
899 prepare(null, VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700900 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700901
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700902 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700903 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
904 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700905 }
906
Jeff Sharkey899223b2012-08-04 15:24:58 -0700907 public synchronized void stopLegacyVpn() {
908 if (mLegacyVpnRunner != null) {
909 mLegacyVpnRunner.exit();
910 mLegacyVpnRunner = null;
911
912 synchronized (LegacyVpnRunner.TAG) {
913 // wait for old thread to completely finish before spinning up
914 // new instance, otherwise state updates can be out of order.
915 }
916 }
917 }
918
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700919 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700920 * Return the information of the current ongoing legacy VPN.
921 */
922 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700923 // Check if the caller is authorized.
924 enforceControlPermission();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700925 if (mLegacyVpnRunner == null) return null;
926
927 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -0700928 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700929 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700930 if (mNetworkInfo.isConnected()) {
931 info.intent = mStatusIntent;
932 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700933 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700934 }
935
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700936 public VpnConfig getLegacyVpnConfig() {
937 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700938 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700939 } else {
940 return null;
941 }
942 }
943
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700944 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700945 * Bringing up a VPN connection takes time, and that is all this thread
946 * does. Here we have plenty of time. The only thing we need to take
947 * care of is responding to interruptions as soon as possible. Otherwise
948 * requests will be piled up. This can be done in a Handler as a state
949 * machine, but it is much easier to read in the current form.
950 */
951 private class LegacyVpnRunner extends Thread {
952 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700953
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700954 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700955 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700956 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700957 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700958 private final AtomicInteger mOuterConnection =
959 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700960
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700961 private long mTimer = -1;
962
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700963 /**
964 * Watch for the outer connection (passing in the constructor) going away.
965 */
966 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
967 @Override
968 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -0700969 if (!mEnableTeardown) return;
970
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700971 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
972 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
973 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
974 NetworkInfo info = (NetworkInfo)intent.getExtra(
975 ConnectivityManager.EXTRA_NETWORK_INFO);
976 if (info != null && !info.isConnectedOrConnecting()) {
977 try {
978 mObserver.interfaceStatusChanged(mOuterInterface, false);
979 } catch (RemoteException e) {}
980 }
981 }
982 }
983 }
984 };
985
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700986 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700987 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700988 mConfig = config;
989 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -0700990 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700991 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700992 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700993
994 // This is the interface which VPN is running on,
995 // mConfig.interfaze will change to point to OUR
996 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700997 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700998 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700999 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001000 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001001
1002 try {
1003 mOuterConnection.set(
1004 mConnService.findConnectionTypeForIface(mOuterInterface));
1005 } catch (Exception e) {
1006 mOuterConnection.set(ConnectivityManager.TYPE_NONE);
1007 }
1008
1009 IntentFilter filter = new IntentFilter();
1010 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1011 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001012 }
1013
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001014 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001015 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001016 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1017 exit();
1018 }
1019 }
1020
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001021 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001022 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001023 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001024 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001025 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001026 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001027 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001028 try {
1029 mContext.unregisterReceiver(mBroadcastReceiver);
1030 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001031 }
1032
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001033 @Override
1034 public void run() {
1035 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001036 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001037 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001038 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001039 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001040 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001041 }
1042 }
1043
1044 private void checkpoint(boolean yield) throws InterruptedException {
1045 long now = SystemClock.elapsedRealtime();
1046 if (mTimer == -1) {
1047 mTimer = now;
1048 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001049 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001050 Thread.sleep(yield ? 200 : 1);
1051 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001052 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001053 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001054 }
1055 }
1056
1057 private void execute() {
1058 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001059 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001060 try {
1061 // Initialize the timer.
1062 checkpoint(false);
1063
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001064 // Wait for the daemons to stop.
1065 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001066 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001067 checkpoint(true);
1068 }
1069 }
1070
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001071 // Clear the previous state.
1072 File state = new File("/data/misc/vpn/state");
1073 state.delete();
1074 if (state.exists()) {
1075 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001076 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001077 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001078 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001079
Chia-chi Yehe9107902011-07-02 01:48:50 -07001080 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001081 boolean restart = false;
1082 for (String[] arguments : mArguments) {
1083 restart = restart || (arguments != null);
1084 }
1085 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001086 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001087 return;
1088 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001089 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001090
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001091 // Start the daemon with arguments.
1092 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001093 String[] arguments = mArguments[i];
1094 if (arguments == null) {
1095 continue;
1096 }
1097
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001098 // Start the daemon.
1099 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001100 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001101
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001102 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001103 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001104 checkpoint(true);
1105 }
1106
1107 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001108 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001109 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001110 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001111
1112 // Wait for the socket to connect.
1113 while (true) {
1114 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001115 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001116 break;
1117 } catch (Exception e) {
1118 // ignore
1119 }
1120 checkpoint(true);
1121 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001122 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001123
1124 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001125 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001126 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001127 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001128 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001129 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001130 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001131 out.write(bytes.length >> 8);
1132 out.write(bytes.length);
1133 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001134 checkpoint(false);
1135 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001136 out.write(0xFF);
1137 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001138 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001139
1140 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001141 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001142 while (true) {
1143 try {
1144 if (in.read() == -1) {
1145 break;
1146 }
1147 } catch (Exception e) {
1148 // ignore
1149 }
1150 checkpoint(true);
1151 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001152 }
1153
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001154 // Wait for the daemons to create the new state.
1155 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001156 // Check if a running daemon is dead.
1157 for (int i = 0; i < mDaemons.length; ++i) {
1158 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001159 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001160 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001161 }
1162 }
1163 checkpoint(true);
1164 }
1165
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001166 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001167 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001168 if (parameters.length != 6) {
1169 throw new IllegalStateException("Cannot parse the state");
1170 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001171
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001172 // Set the interface and the addresses in the config.
1173 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001174
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001175 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001176 // Set the routes if they are not set in the config.
1177 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001178 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001179 }
1180
1181 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001182 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001183 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001184 if (!dnsServers.isEmpty()) {
1185 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1186 }
1187 }
1188
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001189 // Set the search domains if they are not set in the config.
1190 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1191 String searchDomains = parameters[4].trim();
1192 if (!searchDomains.isEmpty()) {
1193 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1194 }
1195 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001196
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001197 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001198 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001199 // Set the start time
1200 mConfig.startTime = SystemClock.elapsedRealtime();
1201
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001202 // Check if the thread is interrupted while we are waiting.
1203 checkpoint(false);
1204
Chia-chi Yehe9107902011-07-02 01:48:50 -07001205 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001206 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001207 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001208 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001209
1210 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001211 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001212 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001213 mAllowIPv4 = mConfig.allowIPv4;
1214 mAllowIPv6 = mConfig.allowIPv6;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001215
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001216 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001217
1218 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001219 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001220 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001221 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001222 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001223 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001224 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001225 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001226 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001227 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001228 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001229 }
1230 }
1231
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001232 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001233 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001234 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001235 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001236 }
1237 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001238
1239 /**
1240 * Monitor the daemons we started, moving to disconnected state if the
1241 * underlying services fail.
1242 */
1243 private void monitorDaemons() {
1244 if (!mNetworkInfo.isConnected()) {
1245 return;
1246 }
1247
1248 try {
1249 while (true) {
1250 Thread.sleep(2000);
1251 for (int i = 0; i < mDaemons.length; i++) {
1252 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1253 return;
1254 }
1255 }
1256 }
1257 } catch (InterruptedException e) {
1258 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1259 } finally {
1260 for (String daemon : mDaemons) {
1261 SystemService.stop(daemon);
1262 }
1263
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001264 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001265 }
1266 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001267 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001268}