blob: 0a8ca6aa1f586db0a84fa332b35eefdedf136ad7 [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;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070024import android.app.Notification;
25import android.app.NotificationManager;
Jeff Sharkey899223b2012-08-04 15:24:58 -070026import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070027import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070028import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070029import android.content.Context;
30import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070031import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070032import android.content.ServiceConnection;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070033import android.content.pm.ApplicationInfo;
34import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040035import android.content.pm.PackageManager.NameNotFoundException;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070036import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070037import android.content.pm.UserInfo;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070038import android.graphics.Bitmap;
39import android.graphics.Canvas;
40import android.graphics.drawable.Drawable;
Jeff Sharkey899223b2012-08-04 15:24:58 -070041import android.net.BaseNetworkStateTracker;
42import android.net.ConnectivityManager;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070043import android.net.IConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070044import android.net.INetworkManagementEventObserver;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070045import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070046import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070047import android.net.LocalSocket;
48import android.net.LocalSocketAddress;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040049import android.net.NetworkAgent;
50import android.net.NetworkCapabilities;
Jeff Sharkey899223b2012-08-04 15:24:58 -070051import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040052import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070053import android.net.NetworkMisc;
Chad Brubakerc0234532014-02-14 13:24:29 -080054import android.net.NetworkUtils;
Jeff Sharkey82f85212012-08-24 11:17:25 -070055import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040056import android.net.UidRange;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070057import android.os.Binder;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080058import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070059import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070060import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040061import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070062import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070063import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070064import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070065import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070066import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070067import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070068import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070069import android.os.UserManager;
Jeff Sharkey82f85212012-08-24 11:17:25 -070070import android.security.Credentials;
71import android.security.KeyStore;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070072import android.util.Log;
Chad Brubakerc2865192013-07-10 14:46:23 -070073import android.util.SparseBooleanArray;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070074
Chad Brubakerc2865192013-07-10 14:46:23 -070075import com.android.internal.annotations.GuardedBy;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070076import com.android.internal.R;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070077import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070078import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -070079import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070080import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070081
Chia-chi Yeh97a61562011-07-14 15:05:05 -070082import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070083import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070084import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070085import java.io.OutputStream;
Chad Brubakerc0234532014-02-14 13:24:29 -080086import java.net.InetAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070087import java.net.Inet4Address;
Elliott Hughesd396a442013-06-28 16:24:48 -070088import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040089import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070090import java.util.Arrays;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040091import java.util.List;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070092import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070093
Jeff Sharkey065b2992012-08-05 14:16:48 -070094import libcore.io.IoUtils;
95
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070096/**
97 * @hide
98 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040099public class Vpn {
100 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700101 private static final String TAG = "Vpn";
102 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400103
Jeff Sharkey899223b2012-08-04 15:24:58 -0700104 // TODO: create separate trackers for each unique VPN to support
105 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700106
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400107 private Context mContext;
108 private NetworkInfo mNetworkInfo;
109 private String mPackage;
110 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700111 private String mInterface;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700112 private boolean mAllowIPv4;
113 private boolean mAllowIPv6;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700114 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700115 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700116 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700117 private volatile boolean mEnableNotif = true;
118 private volatile boolean mEnableTeardown = true;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700119 private final IConnectivityManager mConnService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400120 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700121 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400122 private NetworkAgent mNetworkAgent;
123 private final Looper mLooper;
124 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700125
126 /* list of users using this VPN. */
127 @GuardedBy("this")
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400128 private List<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700129 private BroadcastReceiver mUserIntentReceiver = null;
130
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700131 private final int mUserId;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700132
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400133 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700134 IConnectivityManager connService, int userId) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700135 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400136 mNetd = netService;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700137 mConnService = connService;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700138 mUserId = userId;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400139 mLooper = looper;
140
141 mPackage = VpnConfig.LEGACY_VPN;
142 mOwnerUID = getAppUid(mPackage);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700143
144 try {
145 netService.registerObserver(mObserver);
146 } catch (RemoteException e) {
147 Log.wtf(TAG, "Problem registering observer", e);
148 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700149 if (userId == UserHandle.USER_OWNER) {
150 // Owner's VPN also needs to handle restricted users
151 mUserIntentReceiver = new BroadcastReceiver() {
152 @Override
153 public void onReceive(Context context, Intent intent) {
154 final String action = intent.getAction();
155 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
156 UserHandle.USER_NULL);
157 if (userId == UserHandle.USER_NULL) return;
158
159 if (Intent.ACTION_USER_ADDED.equals(action)) {
160 onUserAdded(userId);
161 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
162 onUserRemoved(userId);
163 }
164 }
165 };
166
167 IntentFilter intentFilter = new IntentFilter();
168 intentFilter.addAction(Intent.ACTION_USER_ADDED);
169 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
170 mContext.registerReceiverAsUser(
171 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
172 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400173
174 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
175 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
176 mNetworkCapabilities = new NetworkCapabilities();
177 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
178 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700179 }
180
Jeff Sharkey57666932013-04-30 17:01:57 -0700181 /**
182 * Set if this object is responsible for showing its own notifications. When
183 * {@code false}, notifications are handled externally by someone else.
184 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700185 public void setEnableNotifications(boolean enableNotif) {
186 mEnableNotif = enableNotif;
187 }
188
Jeff Sharkey57666932013-04-30 17:01:57 -0700189 /**
190 * Set if this object is responsible for watching for {@link NetworkInfo}
191 * teardown. When {@code false}, teardown is handled externally by someone
192 * else.
193 */
194 public void setEnableTeardown(boolean enableTeardown) {
195 mEnableTeardown = enableTeardown;
196 }
197
Jeff Sharkey899223b2012-08-04 15:24:58 -0700198 /**
199 * Update current state, dispaching event to listeners.
200 */
201 private void updateState(DetailedState detailedState, String reason) {
202 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
203 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400204 if (mNetworkAgent != null) {
205 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
206 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700207 }
208
209 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700210 * Prepare for a VPN application. This method is designed to solve
211 * race conditions. It first compares the current prepared package
212 * with {@code oldPackage}. If they are the same, the prepared
213 * package is revoked and replaced with {@code newPackage}. If
214 * {@code oldPackage} is {@code null}, the comparison is omitted.
215 * If {@code newPackage} is the same package or {@code null}, the
216 * revocation is omitted. This method returns {@code true} if the
217 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700218 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700219 * Legacy VPN is handled specially since it is not a real package.
220 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
221 * it can be revoked by itself.
222 *
223 * @param oldPackage The package name of the old VPN application.
224 * @param newPackage The package name of the new VPN application.
225 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700226 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700227 public synchronized boolean prepare(String oldPackage, String newPackage) {
228 // Return false if the package does not match.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700229 if (oldPackage != null && !oldPackage.equals(mPackage)) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700230 return false;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700231 }
232
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700233 // Return true if we do not need to revoke.
234 if (newPackage == null ||
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700235 (newPackage.equals(mPackage) && !newPackage.equals(VpnConfig.LEGACY_VPN))) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700236 return true;
237 }
238
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700239 // Check if the caller is authorized.
240 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700241
Chia-chi Yehe9107902011-07-02 01:48:50 -0700242 // Reset the interface and hide the notification.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700243 if (mInterface != null) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400244 for (UidRange uidRange : mVpnUsers) {
245 hideNotification(uidRange.getStartUser());
Jeff Sharkey899223b2012-08-04 15:24:58 -0700246 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400247 agentDisconnect();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700248 jniReset(mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700249 mInterface = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700250 mVpnUsers = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700251 }
252
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700253 // Revoke the connection or stop LegacyVpnRunner.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700254 if (mConnection != null) {
255 try {
256 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
257 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
258 } catch (Exception e) {
259 // ignore
260 }
261 mContext.unbindService(mConnection);
262 mConnection = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700263 } else if (mLegacyVpnRunner != null) {
264 mLegacyVpnRunner.exit();
265 mLegacyVpnRunner = null;
266 }
267
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400268 long token = Binder.clearCallingIdentity();
269 try {
270 mNetd.denyProtect(mOwnerUID);
271 } catch (Exception e) {
272 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
273 } finally {
274 Binder.restoreCallingIdentity(token);
275 }
276
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700277 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
278 mPackage = newPackage;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400279 mOwnerUID = getAppUid(newPackage);
280 token = Binder.clearCallingIdentity();
281 try {
282 mNetd.allowProtect(mOwnerUID);
283 } catch (Exception e) {
284 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
285 } finally {
286 Binder.restoreCallingIdentity(token);
287 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700288 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700289 updateState(DetailedState.IDLE, "prepare");
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700290 return true;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700291 }
292
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400293 private int getAppUid(String app) {
294 if (app == VpnConfig.LEGACY_VPN) {
295 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700296 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400297 PackageManager pm = mContext.getPackageManager();
298 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700299 try {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400300 result = pm.getPackageUid(app, mUserId);
301 } catch (NameNotFoundException e) {
302 result = -1;
303 }
304 return result;
305 }
306
307 public NetworkInfo getNetworkInfo() {
308 return mNetworkInfo;
309 }
310
311 private void agentConnect() {
312 LinkProperties lp = new LinkProperties();
313 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700314
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400315 boolean hasDefaultRoute = false;
316 for (RouteInfo route : mConfig.routes) {
317 lp.addRoute(route);
318 if (route.isDefaultRoute()) hasDefaultRoute = true;
319 }
320 if (hasDefaultRoute) {
321 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
322 } else {
323 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
324 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700325
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400326 if (mConfig.dnsServers != null) {
327 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700328 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
329 lp.addDnsServer(address);
330 if (address instanceof Inet4Address) {
331 mAllowIPv4 = true;
332 } else {
333 mAllowIPv6 = true;
334 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400335 }
336 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700337
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400338 // Concatenate search domains into a string.
339 StringBuilder buffer = new StringBuilder();
340 if (mConfig.searchDomains != null) {
341 for (String domain : mConfig.searchDomains) {
342 buffer.append(domain).append(' ');
343 }
344 }
345 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700346
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400347 mNetworkInfo.setIsAvailable(true);
348 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700349
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700350 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700351 networkMisc.allowBypass = mConfig.allowBypass;
352
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400353 long token = Binder.clearCallingIdentity();
354 try {
355 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700356 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400357 public void unwanted() {
358 // We are user controlled, not driven by NetworkRequest.
359 };
360 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700361 } finally {
362 Binder.restoreCallingIdentity(token);
363 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700364
365 if (!mAllowIPv4) {
366 mNetworkAgent.blockAddressFamily(AF_INET);
367 }
368 if (!mAllowIPv6) {
369 mNetworkAgent.blockAddressFamily(AF_INET6);
370 }
371
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400372 addVpnUserLocked(mUserId);
373 // If we are owner assign all Restricted Users to this VPN
374 if (mUserId == UserHandle.USER_OWNER) {
375 token = Binder.clearCallingIdentity();
376 List<UserInfo> users;
377 try {
378 users = UserManager.get(mContext).getUsers();
379 } finally {
380 Binder.restoreCallingIdentity(token);
381 }
382 for (UserInfo user : users) {
383 if (user.isRestricted()) {
384 addVpnUserLocked(user.id);
385 }
386 }
387 }
388 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
389 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700390
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400391 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
392 networkInfo.setIsAvailable(false);
393 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
394 if (networkAgent != null) {
395 networkAgent.sendNetworkInfo(networkInfo);
396 }
397 }
398
399 private void agentDisconnect(NetworkAgent networkAgent) {
400 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
401 agentDisconnect(networkInfo, networkAgent);
402 }
403
404 private void agentDisconnect() {
405 if (mNetworkInfo.isConnected()) {
406 agentDisconnect(mNetworkInfo, mNetworkAgent);
407 mNetworkAgent = null;
408 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700409 }
410
411 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700412 * Establish a VPN network and return the file descriptor of the VPN
413 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700414 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700415 *
416 * @param config The parameters to configure the network.
417 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700418 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700419 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700420 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700421 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400422 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700423 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700424 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700425 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700426 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
427 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700428 long token = Binder.clearCallingIdentity();
429 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700430 // Restricted users are not allowed to create VPNs, they are tied to Owner
431 UserInfo user = mgr.getUserInfo(mUserId);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400432 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700433 throw new SecurityException("Restricted users cannot establish VPNs");
434 }
435
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700436 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
437 null, 0, mUserId);
438 if (info == null) {
439 throw new SecurityException("Cannot find " + config.user);
440 }
441 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
442 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
443 }
444 } catch (RemoteException e) {
445 throw new SecurityException("Cannot find " + config.user);
446 } finally {
447 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700448 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700449
Chad Brubaker850eb672014-03-21 21:02:47 +0000450 // Save the old config in case we need to go back.
451 VpnConfig oldConfig = mConfig;
452 String oldInterface = mInterface;
453 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400454 NetworkAgent oldNetworkAgent = mNetworkAgent;
455 mNetworkAgent = null;
456 List<UidRange> oldUsers = mVpnUsers;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700457 boolean oldAllowIPv4 = mAllowIPv4;
458 boolean oldAllowIPv6 = mAllowIPv6;
Chad Brubaker850eb672014-03-21 21:02:47 +0000459
Chia-chi Yehe9107902011-07-02 01:48:50 -0700460 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700461 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700462 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700463 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700464 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700465
Chad Brubakerc2865192013-07-10 14:46:23 -0700466 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700467 StringBuilder builder = new StringBuilder();
468 for (LinkAddress address : config.addresses) {
469 builder.append(" " + address);
470 }
471 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700472 throw new IllegalArgumentException("At least one address must be specified");
473 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700474 Connection connection = new Connection();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700475 if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
476 new UserHandle(mUserId))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700477 throw new IllegalStateException("Cannot bind " + config.user);
478 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000479
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700480 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700481 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700482
483 // Fill more values.
484 config.user = mPackage;
485 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700486 config.startTime = SystemClock.elapsedRealtime();
487 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000488
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700489 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400490 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700491 mAllowIPv4 = mConfig.allowIPv4;
492 mAllowIPv6 = mConfig.allowIPv6;
493
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400494 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000495
496 if (oldConnection != null) {
497 mContext.unbindService(oldConnection);
498 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400499 // Remove the old tun's user forwarding rules
500 // The new tun's user rules have already been added so they will take over
501 // as rules are deleted. This prevents data leakage as the rules are moved over.
502 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000503 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000504 jniReset(oldInterface);
505 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700506
507 try {
508 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
509 } catch (IOException e) {
510 throw new IllegalStateException(
511 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
512 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000513 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000514 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400515 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000516 // restore old state
517 mConfig = oldConfig;
518 mConnection = oldConnection;
519 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400520 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000521 mInterface = oldInterface;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700522 mAllowIPv4 = oldAllowIPv4;
523 mAllowIPv6 = oldAllowIPv6;
Chad Brubaker850eb672014-03-21 21:02:47 +0000524 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700525 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000526 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700527 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700528 }
529
Chad Brubakerc2865192013-07-10 14:46:23 -0700530 private boolean isRunningLocked() {
531 return mVpnUsers != null;
532 }
533
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400534 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Chad Brubakerc2865192013-07-10 14:46:23 -0700535 private void addVpnUserLocked(int user) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700536 if (!isRunningLocked()) {
537 throw new IllegalStateException("VPN is not active");
538 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700539
Chad Brubakerc2865192013-07-10 14:46:23 -0700540 // add the user
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400541 mVpnUsers.add(UidRange.createForUser(user));
Chad Brubakerc2865192013-07-10 14:46:23 -0700542
543 // show the notification
544 if (!mPackage.equals(VpnConfig.LEGACY_VPN)) {
545 // Load everything for the user's notification
546 PackageManager pm = mContext.getPackageManager();
547 ApplicationInfo app = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400548 final long token = Binder.clearCallingIdentity();
Chad Brubakerc2865192013-07-10 14:46:23 -0700549 try {
550 app = AppGlobals.getPackageManager().getApplicationInfo(mPackage, 0, mUserId);
551 } catch (RemoteException e) {
552 throw new IllegalStateException("Invalid application");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400553 } finally {
554 Binder.restoreCallingIdentity(token);
Chad Brubakerc2865192013-07-10 14:46:23 -0700555 }
556 String label = app.loadLabel(pm).toString();
557 // Load the icon and convert it into a bitmap.
558 Drawable icon = app.loadIcon(pm);
559 Bitmap bitmap = null;
560 if (icon.getIntrinsicWidth() > 0 && icon.getIntrinsicHeight() > 0) {
561 int width = mContext.getResources().getDimensionPixelSize(
562 android.R.dimen.notification_large_icon_width);
563 int height = mContext.getResources().getDimensionPixelSize(
564 android.R.dimen.notification_large_icon_height);
565 icon.setBounds(0, 0, width, height);
566 bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
567 Canvas c = new Canvas(bitmap);
568 icon.draw(c);
569 c.setBitmap(null);
570 }
571 showNotification(label, bitmap, user);
572 } else {
573 showNotification(null, null, user);
574 }
575 }
576
577 private void removeVpnUserLocked(int user) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700578 if (!isRunningLocked()) {
579 throw new IllegalStateException("VPN is not active");
580 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400581 UidRange uidRange = UidRange.createForUser(user);
582 if (mNetworkAgent != null) {
583 mNetworkAgent.removeUidRanges(new UidRange[] { uidRange });
584 }
585 mVpnUsers.remove(uidRange);
Chad Brubakerc2865192013-07-10 14:46:23 -0700586 hideNotification(user);
587 }
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) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400654 for (UidRange uidRange : mVpnUsers) {
655 hideNotification(uidRange.getStartUser());
Jeff Sharkey899223b2012-08-04 15:24:58 -0700656 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400657 mVpnUsers = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700658 mInterface = null;
659 if (mConnection != null) {
660 mContext.unbindService(mConnection);
661 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400662 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700663 } else if (mLegacyVpnRunner != null) {
664 mLegacyVpnRunner.exit();
665 mLegacyVpnRunner = null;
666 }
667 }
668 }
669 }
670 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700671
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700672 private void enforceControlPermission() {
673 // System user is allowed to control VPN.
674 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
675 return;
676 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700677 int appId = UserHandle.getAppId(Binder.getCallingUid());
678 final long token = Binder.clearCallingIdentity();
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700679 try {
Nick Kralevich212a1952013-10-18 17:48:39 -0700680 // System VPN dialogs are also allowed to control VPN.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700681 PackageManager pm = mContext.getPackageManager();
682 ApplicationInfo app = pm.getApplicationInfo(VpnConfig.DIALOGS_PACKAGE, 0);
Nick Kralevich212a1952013-10-18 17:48:39 -0700683 if (((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) && (appId == app.uid)) {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700684 return;
685 }
686 } catch (Exception e) {
687 // ignore
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700688 } finally {
689 Binder.restoreCallingIdentity(token);
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700690 }
691
692 throw new SecurityException("Unauthorized Caller");
693 }
694
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700695 private class Connection implements ServiceConnection {
696 private IBinder mService;
697
698 @Override
699 public void onServiceConnected(ComponentName name, IBinder service) {
700 mService = service;
701 }
702
703 @Override
704 public void onServiceDisconnected(ComponentName name) {
705 mService = null;
706 }
707 }
708
Chad Brubakerc2865192013-07-10 14:46:23 -0700709 private void showNotification(String label, Bitmap icon, int user) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700710 if (!mEnableNotif) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400711 final long token = Binder.clearCallingIdentity();
712 try {
713 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700714
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400715 NotificationManager nm = (NotificationManager)
716 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700717
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400718 if (nm != null) {
719 String title = (label == null) ? mContext.getString(R.string.vpn_title) :
720 mContext.getString(R.string.vpn_title_long, label);
721 String text = (mConfig.session == null) ? mContext.getString(R.string.vpn_text) :
722 mContext.getString(R.string.vpn_text_long, mConfig.session);
Chia-chi Yeha4b87b52011-06-30 23:21:55 -0700723
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400724 Notification notification = new Notification.Builder(mContext)
725 .setSmallIcon(R.drawable.vpn_connected)
726 .setLargeIcon(icon)
727 .setContentTitle(title)
728 .setContentText(text)
729 .setContentIntent(mStatusIntent)
730 .setDefaults(0)
731 .setOngoing(true)
732 .build();
733 nm.notifyAsUser(null, R.drawable.vpn_connected, notification, new UserHandle(user));
734 }
735 } finally {
736 Binder.restoreCallingIdentity(token);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700737 }
738 }
739
Chad Brubakerc2865192013-07-10 14:46:23 -0700740 private void hideNotification(int user) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700741 if (!mEnableNotif) return;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700742 mStatusIntent = null;
743
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700744 NotificationManager nm = (NotificationManager)
745 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
746
747 if (nm != null) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400748 final long token = Binder.clearCallingIdentity();
749 try {
750 nm.cancelAsUser(null, R.drawable.vpn_connected, new UserHandle(user));
751 } finally {
752 Binder.restoreCallingIdentity(token);
753 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700754 }
755 }
756
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700757 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700758 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700759 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700760 private native void jniReset(String interfaze);
761 private native int jniCheck(String interfaze);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700762
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900763 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
764 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700765 // Currently legacy VPN only works on IPv4.
766 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900767 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700768 }
769 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700770
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900771 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700772 }
773
774 /**
775 * Start legacy VPN, controlling native daemons as needed. Creates a
776 * secondary thread to perform connection work, returning quickly.
777 */
778 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800779 enforceControlPermission();
Kenny Rootb9594ce2013-02-14 10:18:38 -0800780 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700781 throw new IllegalStateException("KeyStore isn't unlocked");
782 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400783 UserManager mgr = UserManager.get(mContext);
784 UserInfo user = mgr.getUserInfo(mUserId);
785 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
786 throw new SecurityException("Restricted users cannot establish VPNs");
787 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700788
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900789 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
790 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
791 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700792
793 // Load certificates.
794 String privateKey = "";
795 String userCert = "";
796 String caCert = "";
797 String serverCert = "";
798 if (!profile.ipsecUserCert.isEmpty()) {
799 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
800 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700801 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700802 }
803 if (!profile.ipsecCaCert.isEmpty()) {
804 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700805 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700806 }
807 if (!profile.ipsecServerCert.isEmpty()) {
808 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700809 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700810 }
811 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
812 throw new IllegalStateException("Cannot load credentials");
813 }
814
815 // Prepare arguments for racoon.
816 String[] racoon = null;
817 switch (profile.type) {
818 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
819 racoon = new String[] {
820 iface, profile.server, "udppsk", profile.ipsecIdentifier,
821 profile.ipsecSecret, "1701",
822 };
823 break;
824 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
825 racoon = new String[] {
826 iface, profile.server, "udprsa", privateKey, userCert,
827 caCert, serverCert, "1701",
828 };
829 break;
830 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
831 racoon = new String[] {
832 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
833 profile.ipsecSecret, profile.username, profile.password, "", gateway,
834 };
835 break;
836 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
837 racoon = new String[] {
838 iface, profile.server, "xauthrsa", privateKey, userCert,
839 caCert, serverCert, profile.username, profile.password, "", gateway,
840 };
841 break;
842 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
843 racoon = new String[] {
844 iface, profile.server, "hybridrsa",
845 caCert, serverCert, profile.username, profile.password, "", gateway,
846 };
847 break;
848 }
849
850 // Prepare arguments for mtpd.
851 String[] mtpd = null;
852 switch (profile.type) {
853 case VpnProfile.TYPE_PPTP:
854 mtpd = new String[] {
855 iface, "pptp", profile.server, "1723",
856 "name", profile.username, "password", profile.password,
857 "linkname", "vpn", "refuse-eap", "nodefaultroute",
858 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
859 (profile.mppe ? "+mppe" : "nomppe"),
860 };
861 break;
862 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
863 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
864 mtpd = new String[] {
865 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
866 "name", profile.username, "password", profile.password,
867 "linkname", "vpn", "refuse-eap", "nodefaultroute",
868 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
869 };
870 break;
871 }
872
873 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700874 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700875 config.user = profile.key;
876 config.interfaze = iface;
877 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700878
879 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700880 if (!profile.dnsServers.isEmpty()) {
881 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
882 }
883 if (!profile.searchDomains.isEmpty()) {
884 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
885 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700886 startLegacyVpn(config, racoon, mtpd);
887 }
888
889 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
890 stopLegacyVpn();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700891
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700892 // Prepare for the new request. This also checks the caller.
893 prepare(null, VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700894 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700895
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700896 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700897 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
898 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700899 }
900
Jeff Sharkey899223b2012-08-04 15:24:58 -0700901 public synchronized void stopLegacyVpn() {
902 if (mLegacyVpnRunner != null) {
903 mLegacyVpnRunner.exit();
904 mLegacyVpnRunner = null;
905
906 synchronized (LegacyVpnRunner.TAG) {
907 // wait for old thread to completely finish before spinning up
908 // new instance, otherwise state updates can be out of order.
909 }
910 }
911 }
912
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700913 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700914 * Return the information of the current ongoing legacy VPN.
915 */
916 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700917 // Check if the caller is authorized.
918 enforceControlPermission();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700919 if (mLegacyVpnRunner == null) return null;
920
921 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -0700922 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700923 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
924 if (mNetworkInfo.isConnected()) {
925 info.intent = mStatusIntent;
926 }
927 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700928 }
929
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700930 public VpnConfig getLegacyVpnConfig() {
931 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700932 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700933 } else {
934 return null;
935 }
936 }
937
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700938 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700939 * Bringing up a VPN connection takes time, and that is all this thread
940 * does. Here we have plenty of time. The only thing we need to take
941 * care of is responding to interruptions as soon as possible. Otherwise
942 * requests will be piled up. This can be done in a Handler as a state
943 * machine, but it is much easier to read in the current form.
944 */
945 private class LegacyVpnRunner extends Thread {
946 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700947
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700948 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700949 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700950 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700951 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700952 private final AtomicInteger mOuterConnection =
953 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700954
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700955 private long mTimer = -1;
956
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700957 /**
958 * Watch for the outer connection (passing in the constructor) going away.
959 */
960 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
961 @Override
962 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -0700963 if (!mEnableTeardown) return;
964
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700965 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
966 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
967 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
968 NetworkInfo info = (NetworkInfo)intent.getExtra(
969 ConnectivityManager.EXTRA_NETWORK_INFO);
970 if (info != null && !info.isConnectedOrConnecting()) {
971 try {
972 mObserver.interfaceStatusChanged(mOuterInterface, false);
973 } catch (RemoteException e) {}
974 }
975 }
976 }
977 }
978 };
979
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700980 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700981 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700982 mConfig = config;
983 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -0700984 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700985 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700986 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700987
988 // This is the interface which VPN is running on,
989 // mConfig.interfaze will change to point to OUR
990 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700991 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700992 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700993 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700994 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700995
996 try {
997 mOuterConnection.set(
998 mConnService.findConnectionTypeForIface(mOuterInterface));
999 } catch (Exception e) {
1000 mOuterConnection.set(ConnectivityManager.TYPE_NONE);
1001 }
1002
1003 IntentFilter filter = new IntentFilter();
1004 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1005 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001006 }
1007
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001008 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001009 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001010 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1011 exit();
1012 }
1013 }
1014
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001015 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001016 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001017 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001018 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001019 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001020 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001021 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001022 try {
1023 mContext.unregisterReceiver(mBroadcastReceiver);
1024 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001025 }
1026
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001027 @Override
1028 public void run() {
1029 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001030 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001031 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001032 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001033 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001034 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001035 }
1036 }
1037
1038 private void checkpoint(boolean yield) throws InterruptedException {
1039 long now = SystemClock.elapsedRealtime();
1040 if (mTimer == -1) {
1041 mTimer = now;
1042 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001043 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001044 Thread.sleep(yield ? 200 : 1);
1045 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001046 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001047 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001048 }
1049 }
1050
1051 private void execute() {
1052 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001053 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001054 try {
1055 // Initialize the timer.
1056 checkpoint(false);
1057
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001058 // Wait for the daemons to stop.
1059 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001060 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001061 checkpoint(true);
1062 }
1063 }
1064
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001065 // Clear the previous state.
1066 File state = new File("/data/misc/vpn/state");
1067 state.delete();
1068 if (state.exists()) {
1069 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001070 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001071 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001072 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001073
Chia-chi Yehe9107902011-07-02 01:48:50 -07001074 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001075 boolean restart = false;
1076 for (String[] arguments : mArguments) {
1077 restart = restart || (arguments != null);
1078 }
1079 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001080 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001081 return;
1082 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001083 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001084
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001085 // Start the daemon with arguments.
1086 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001087 String[] arguments = mArguments[i];
1088 if (arguments == null) {
1089 continue;
1090 }
1091
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001092 // Start the daemon.
1093 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001094 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001095
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001096 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001097 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001098 checkpoint(true);
1099 }
1100
1101 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001102 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001103 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001104 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001105
1106 // Wait for the socket to connect.
1107 while (true) {
1108 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001109 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001110 break;
1111 } catch (Exception e) {
1112 // ignore
1113 }
1114 checkpoint(true);
1115 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001116 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001117
1118 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001119 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001120 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001121 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001122 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001123 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001124 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001125 out.write(bytes.length >> 8);
1126 out.write(bytes.length);
1127 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001128 checkpoint(false);
1129 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001130 out.write(0xFF);
1131 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001132 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001133
1134 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001135 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001136 while (true) {
1137 try {
1138 if (in.read() == -1) {
1139 break;
1140 }
1141 } catch (Exception e) {
1142 // ignore
1143 }
1144 checkpoint(true);
1145 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001146 }
1147
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001148 // Wait for the daemons to create the new state.
1149 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001150 // Check if a running daemon is dead.
1151 for (int i = 0; i < mDaemons.length; ++i) {
1152 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001153 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001154 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001155 }
1156 }
1157 checkpoint(true);
1158 }
1159
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001160 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001161 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001162 if (parameters.length != 6) {
1163 throw new IllegalStateException("Cannot parse the state");
1164 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001165
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001166 // Set the interface and the addresses in the config.
1167 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001168
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001169 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001170 // Set the routes if they are not set in the config.
1171 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001172 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001173 }
1174
1175 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001176 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001177 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001178 if (!dnsServers.isEmpty()) {
1179 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1180 }
1181 }
1182
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001183 // Set the search domains if they are not set in the config.
1184 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1185 String searchDomains = parameters[4].trim();
1186 if (!searchDomains.isEmpty()) {
1187 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1188 }
1189 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001190
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001191 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001192 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001193 // Set the start time
1194 mConfig.startTime = SystemClock.elapsedRealtime();
1195
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001196 // Check if the thread is interrupted while we are waiting.
1197 checkpoint(false);
1198
Chia-chi Yehe9107902011-07-02 01:48:50 -07001199 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001200 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001201 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001202 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001203
1204 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001205 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001206 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001207 mAllowIPv4 = mConfig.allowIPv4;
1208 mAllowIPv6 = mConfig.allowIPv6;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001209
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001210 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001211
1212 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001213 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001214 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001215 Log.i(TAG, "Aborting", e);
Chia-chi Yehe9107902011-07-02 01:48:50 -07001216 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001217 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001218 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001219 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001220 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001221 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001222 }
1223 }
1224
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001225 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001226 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001227 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001228 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001229 }
1230 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001231
1232 /**
1233 * Monitor the daemons we started, moving to disconnected state if the
1234 * underlying services fail.
1235 */
1236 private void monitorDaemons() {
1237 if (!mNetworkInfo.isConnected()) {
1238 return;
1239 }
1240
1241 try {
1242 while (true) {
1243 Thread.sleep(2000);
1244 for (int i = 0; i < mDaemons.length; i++) {
1245 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1246 return;
1247 }
1248 }
1249 }
1250 } catch (InterruptedException e) {
1251 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1252 } finally {
1253 for (String daemon : mDaemons) {
1254 SystemService.stop(daemon);
1255 }
1256
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001257 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001258 }
1259 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001260 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001261}