blob: 03c05ecd464da5574c7a2f71e21963c35d6a5f70 [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;
Paul Jensen0784eea2014-08-19 16:00:24 -040020import static android.os.UserHandle.PER_USER_RANGE;
Lorenzo Colitti50262792014-09-19 01:53:35 +090021import static android.net.RouteInfo.RTN_THROW;
Lorenzo Colitti60446162014-09-20 00:14:31 +090022import static android.net.RouteInfo.RTN_UNREACHABLE;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -070023import static android.system.OsConstants.AF_INET;
24import static android.system.OsConstants.AF_INET6;
Jeff Sharkey899223b2012-08-04 15:24:58 -070025
Jeff Davidsonbc19c182014-11-11 13:20:01 -080026import android.Manifest;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070027import android.app.AppGlobals;
Jeff Davidson05542602014-08-11 14:07:27 -070028import android.app.AppOpsManager;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -070029import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070030import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070031import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070032import android.content.Context;
33import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070034import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070035import android.content.ServiceConnection;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070036import android.content.pm.ApplicationInfo;
37import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040038import android.content.pm.PackageManager.NameNotFoundException;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070039import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070040import android.content.pm.UserInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070041import android.net.ConnectivityManager;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070042import android.net.IConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070043import android.net.INetworkManagementEventObserver;
Lorenzo Colitti50262792014-09-19 01:53:35 +090044import android.net.IpPrefix;
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;
Jeff Sharkey82f85212012-08-24 11:17:25 -070054import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040055import android.net.UidRange;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070056import android.os.Binder;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080057import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070058import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070059import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040060import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070061import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070062import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070063import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070064import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070065import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070066import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070067import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070068import android.os.UserManager;
Jeff Sharkey82f85212012-08-24 11:17:25 -070069import android.security.Credentials;
70import android.security.KeyStore;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070071import android.util.Log;
72
Chad Brubakerc2865192013-07-10 14:46:23 -070073import com.android.internal.annotations.GuardedBy;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070074import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070075import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -070076import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070077import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070078
Jeff Davidson05542602014-08-11 14:07:27 -070079import libcore.io.IoUtils;
80
Chia-chi Yeh97a61562011-07-14 15:05:05 -070081import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070082import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070083import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070084import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070085import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -070086import java.net.Inet6Address;
87import java.net.InetAddress;
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;
Paul Jensen0784eea2014-08-19 16:00:24 -040092import java.util.SortedSet;
93import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070094import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070095
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;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700112 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700113 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700114 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700115 private volatile boolean mEnableTeardown = true;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700116 private final IConnectivityManager mConnService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400117 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700118 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400119 private NetworkAgent mNetworkAgent;
120 private final Looper mLooper;
121 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700122
123 /* list of users using this VPN. */
124 @GuardedBy("this")
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400125 private List<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700126 private BroadcastReceiver mUserIntentReceiver = null;
127
Paul Jensen0784eea2014-08-19 16:00:24 -0400128 // Handle of user initiating VPN.
129 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700130
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400131 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Paul Jensen0784eea2014-08-19 16:00:24 -0400132 IConnectivityManager connService, int userHandle) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700133 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400134 mNetd = netService;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700135 mConnService = connService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400136 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400137 mLooper = looper;
138
139 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400140 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700141
142 try {
143 netService.registerObserver(mObserver);
144 } catch (RemoteException e) {
145 Log.wtf(TAG, "Problem registering observer", e);
146 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400147 if (userHandle == UserHandle.USER_OWNER) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700148 // Owner's VPN also needs to handle restricted users
149 mUserIntentReceiver = new BroadcastReceiver() {
150 @Override
151 public void onReceive(Context context, Intent intent) {
152 final String action = intent.getAction();
Paul Jensen0784eea2014-08-19 16:00:24 -0400153 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Chad Brubakerc2865192013-07-10 14:46:23 -0700154 UserHandle.USER_NULL);
Paul Jensen0784eea2014-08-19 16:00:24 -0400155 if (userHandle == UserHandle.USER_NULL) return;
Chad Brubakerc2865192013-07-10 14:46:23 -0700156
157 if (Intent.ACTION_USER_ADDED.equals(action)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400158 onUserAdded(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700159 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400160 onUserRemoved(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700161 }
162 }
163 };
164
165 IntentFilter intentFilter = new IntentFilter();
166 intentFilter.addAction(Intent.ACTION_USER_ADDED);
167 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
168 mContext.registerReceiverAsUser(
169 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
170 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400171
172 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
173 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
174 mNetworkCapabilities = new NetworkCapabilities();
175 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
176 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700177 }
178
Jeff Sharkey57666932013-04-30 17:01:57 -0700179 /**
Jeff Sharkey57666932013-04-30 17:01:57 -0700180 * Set if this object is responsible for watching for {@link NetworkInfo}
181 * teardown. When {@code false}, teardown is handled externally by someone
182 * else.
183 */
184 public void setEnableTeardown(boolean enableTeardown) {
185 mEnableTeardown = enableTeardown;
186 }
187
Jeff Sharkey899223b2012-08-04 15:24:58 -0700188 /**
189 * Update current state, dispaching event to listeners.
190 */
191 private void updateState(DetailedState detailedState, String reason) {
192 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
193 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400194 if (mNetworkAgent != null) {
195 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
196 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700197 }
198
199 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700200 * Prepare for a VPN application. This method is designed to solve
201 * race conditions. It first compares the current prepared package
202 * with {@code oldPackage}. If they are the same, the prepared
203 * package is revoked and replaced with {@code newPackage}. If
204 * {@code oldPackage} is {@code null}, the comparison is omitted.
205 * If {@code newPackage} is the same package or {@code null}, the
206 * revocation is omitted. This method returns {@code true} if the
207 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700208 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700209 * Legacy VPN is handled specially since it is not a real package.
210 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
211 * it can be revoked by itself.
212 *
213 * @param oldPackage The package name of the old VPN application.
214 * @param newPackage The package name of the new VPN application.
215 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700216 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700217 public synchronized boolean prepare(String oldPackage, String newPackage) {
218 // Return false if the package does not match.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700219 if (oldPackage != null && getAppUid(oldPackage, mUserHandle) != mOwnerUID) {
Jeff Davidson05542602014-08-11 14:07:27 -0700220 // The package doesn't match. If this VPN was not previously authorized, return false
221 // to force user authorization. Otherwise, revoke the VPN anyway.
222 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
223 long token = Binder.clearCallingIdentity();
224 try {
225 // This looks bizarre, but it is what ConfirmDialog in VpnDialogs is doing when
226 // the user clicks through to allow the VPN to consent. So we are emulating the
227 // action of the dialog without actually showing it.
228 prepare(null, oldPackage);
229 } finally {
230 Binder.restoreCallingIdentity(token);
231 }
232 return true;
233 }
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700234 return false;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700235 }
236
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700237 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700238 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
239 getAppUid(newPackage, mUserHandle) == mOwnerUID)) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700240 return true;
241 }
242
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700243 // Check if the caller is authorized.
244 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700245
Jeff Davidson05542602014-08-11 14:07:27 -0700246 // Reset the interface.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700247 if (mInterface != null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700248 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400249 agentDisconnect();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700250 jniReset(mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700251 mInterface = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700252 mVpnUsers = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700253 }
254
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700255 // Revoke the connection or stop LegacyVpnRunner.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700256 if (mConnection != null) {
257 try {
258 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
259 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
260 } catch (Exception e) {
261 // ignore
262 }
263 mContext.unbindService(mConnection);
264 mConnection = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700265 } else if (mLegacyVpnRunner != null) {
266 mLegacyVpnRunner.exit();
267 mLegacyVpnRunner = null;
268 }
269
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400270 long token = Binder.clearCallingIdentity();
271 try {
272 mNetd.denyProtect(mOwnerUID);
273 } catch (Exception e) {
274 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
275 } finally {
276 Binder.restoreCallingIdentity(token);
277 }
278
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700279 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
280 mPackage = newPackage;
Paul Jensen0784eea2014-08-19 16:00:24 -0400281 mOwnerUID = getAppUid(newPackage, mUserHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400282 token = Binder.clearCallingIdentity();
283 try {
284 mNetd.allowProtect(mOwnerUID);
285 } catch (Exception e) {
286 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
287 } finally {
288 Binder.restoreCallingIdentity(token);
289 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700290 mConfig = null;
Jeff Davidson05542602014-08-11 14:07:27 -0700291
Jeff Sharkey899223b2012-08-04 15:24:58 -0700292 updateState(DetailedState.IDLE, "prepare");
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700293 return true;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700294 }
295
Jeff Davidson05542602014-08-11 14:07:27 -0700296 /**
297 * Set whether the current package has the ability to launch VPNs without user intervention.
298 */
299 public void setPackageAuthorization(boolean authorized) {
300 // Check if the caller is authorized.
301 enforceControlPermission();
302
303 if (mPackage == null || VpnConfig.LEGACY_VPN.equals(mPackage)) {
304 return;
305 }
306
307 long token = Binder.clearCallingIdentity();
308 try {
309 AppOpsManager appOps =
310 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
311 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, mOwnerUID, mPackage,
312 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
313 } catch (Exception e) {
314 Log.wtf(TAG, "Failed to set app ops for package " + mPackage, e);
315 } finally {
316 Binder.restoreCallingIdentity(token);
317 }
318 }
319
320 private boolean isVpnUserPreConsented(String packageName) {
321 AppOpsManager appOps =
322 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
323
324 // Verify that the caller matches the given package and has permission to activate VPNs.
325 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
326 packageName) == AppOpsManager.MODE_ALLOWED;
327 }
328
Paul Jensen0784eea2014-08-19 16:00:24 -0400329 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700330 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400331 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700332 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400333 PackageManager pm = mContext.getPackageManager();
334 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700335 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400336 result = pm.getPackageUid(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400337 } catch (NameNotFoundException e) {
338 result = -1;
339 }
340 return result;
341 }
342
343 public NetworkInfo getNetworkInfo() {
344 return mNetworkInfo;
345 }
346
Lorenzo Colitti60446162014-09-20 00:14:31 +0900347 private LinkProperties makeLinkProperties() {
348 boolean allowIPv4 = mConfig.allowIPv4;
349 boolean allowIPv6 = mConfig.allowIPv6;
350
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400351 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900352
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400353 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700354
Lorenzo Colitti60446162014-09-20 00:14:31 +0900355 if (mConfig.addresses != null) {
356 for (LinkAddress address : mConfig.addresses) {
357 lp.addLinkAddress(address);
358 allowIPv4 |= address.getAddress() instanceof Inet4Address;
359 allowIPv6 |= address.getAddress() instanceof Inet6Address;
360 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400361 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900362
363 if (mConfig.routes != null) {
364 for (RouteInfo route : mConfig.routes) {
365 lp.addRoute(route);
366 InetAddress address = route.getDestination().getAddress();
367 allowIPv4 |= address instanceof Inet4Address;
368 allowIPv6 |= address instanceof Inet6Address;
369 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400370 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700371
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400372 if (mConfig.dnsServers != null) {
373 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700374 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
375 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900376 allowIPv4 |= address instanceof Inet4Address;
377 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400378 }
379 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700380
Lorenzo Colitti60446162014-09-20 00:14:31 +0900381 if (!allowIPv4) {
382 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
383 }
384 if (!allowIPv6) {
385 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
386 }
387
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400388 // Concatenate search domains into a string.
389 StringBuilder buffer = new StringBuilder();
390 if (mConfig.searchDomains != null) {
391 for (String domain : mConfig.searchDomains) {
392 buffer.append(domain).append(' ');
393 }
394 }
395 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700396
Lorenzo Colitti60446162014-09-20 00:14:31 +0900397 // TODO: Stop setting the MTU in jniCreate and set it here.
398
399 return lp;
400 }
401
402 private void agentConnect() {
403 LinkProperties lp = makeLinkProperties();
404
405 if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
406 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
407 } else {
408 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
409 }
410
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400411 mNetworkInfo.setIsAvailable(true);
412 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700413
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700414 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700415 networkMisc.allowBypass = mConfig.allowBypass;
416
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400417 long token = Binder.clearCallingIdentity();
418 try {
419 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700420 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700421 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400422 public void unwanted() {
423 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700424 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400425 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700426 } finally {
427 Binder.restoreCallingIdentity(token);
428 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700429
Paul Jensen0784eea2014-08-19 16:00:24 -0400430 addVpnUserLocked(mUserHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400431 // If we are owner assign all Restricted Users to this VPN
Paul Jensen0784eea2014-08-19 16:00:24 -0400432 if (mUserHandle == UserHandle.USER_OWNER) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400433 token = Binder.clearCallingIdentity();
434 List<UserInfo> users;
435 try {
436 users = UserManager.get(mContext).getUsers();
437 } finally {
438 Binder.restoreCallingIdentity(token);
439 }
440 for (UserInfo user : users) {
441 if (user.isRestricted()) {
442 addVpnUserLocked(user.id);
443 }
444 }
445 }
446 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
447 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700448
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400449 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
450 networkInfo.setIsAvailable(false);
451 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
452 if (networkAgent != null) {
453 networkAgent.sendNetworkInfo(networkInfo);
454 }
455 }
456
457 private void agentDisconnect(NetworkAgent networkAgent) {
458 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
459 agentDisconnect(networkInfo, networkAgent);
460 }
461
462 private void agentDisconnect() {
463 if (mNetworkInfo.isConnected()) {
464 agentDisconnect(mNetworkInfo, mNetworkAgent);
465 mNetworkAgent = null;
466 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700467 }
468
469 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700470 * Establish a VPN network and return the file descriptor of the VPN
471 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700472 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700473 *
474 * @param config The parameters to configure the network.
475 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700476 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700477 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700478 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700479 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400480 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700481 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700482 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700483 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700484 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
485 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700486 long token = Binder.clearCallingIdentity();
487 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700488 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400489 UserInfo user = mgr.getUserInfo(mUserHandle);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400490 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700491 throw new SecurityException("Restricted users cannot establish VPNs");
492 }
493
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700494 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400495 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700496 if (info == null) {
497 throw new SecurityException("Cannot find " + config.user);
498 }
499 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
500 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
501 }
502 } catch (RemoteException e) {
503 throw new SecurityException("Cannot find " + config.user);
504 } finally {
505 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700506 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700507
Chad Brubaker850eb672014-03-21 21:02:47 +0000508 // Save the old config in case we need to go back.
509 VpnConfig oldConfig = mConfig;
510 String oldInterface = mInterface;
511 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400512 NetworkAgent oldNetworkAgent = mNetworkAgent;
513 mNetworkAgent = null;
514 List<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000515
Chia-chi Yehe9107902011-07-02 01:48:50 -0700516 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700517 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700518 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700519 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700520 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700521
Chad Brubakerc2865192013-07-10 14:46:23 -0700522 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700523 StringBuilder builder = new StringBuilder();
524 for (LinkAddress address : config.addresses) {
525 builder.append(" " + address);
526 }
527 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700528 throw new IllegalArgumentException("At least one address must be specified");
529 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700530 Connection connection = new Connection();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700531 if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
Paul Jensen0784eea2014-08-19 16:00:24 -0400532 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700533 throw new IllegalStateException("Cannot bind " + config.user);
534 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000535
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700536 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700537 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700538
539 // Fill more values.
540 config.user = mPackage;
541 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700542 config.startTime = SystemClock.elapsedRealtime();
543 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000544
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700545 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400546 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700547
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400548 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000549
550 if (oldConnection != null) {
551 mContext.unbindService(oldConnection);
552 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400553 // Remove the old tun's user forwarding rules
554 // The new tun's user rules have already been added so they will take over
555 // as rules are deleted. This prevents data leakage as the rules are moved over.
556 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000557 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000558 jniReset(oldInterface);
559 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700560
561 try {
562 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
563 } catch (IOException e) {
564 throw new IllegalStateException(
565 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
566 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000567 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000568 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400569 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000570 // restore old state
571 mConfig = oldConfig;
572 mConnection = oldConnection;
573 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400574 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000575 mInterface = oldInterface;
576 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700577 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000578 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700579 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700580 }
581
Chad Brubakerc2865192013-07-10 14:46:23 -0700582 private boolean isRunningLocked() {
583 return mVpnUsers != null;
584 }
585
Paul Jensen0784eea2014-08-19 16:00:24 -0400586 // Note: Return type guarantees results are deduped and sorted, which callers require.
587 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
588 SortedSet<Integer> uids = new TreeSet<Integer>();
589 for (String app : packageNames) {
590 int uid = getAppUid(app, userHandle);
591 if (uid != -1) uids.add(uid);
592 }
593 return uids;
594 }
595
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400596 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Paul Jensen0784eea2014-08-19 16:00:24 -0400597 private void addVpnUserLocked(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700598 if (!isRunningLocked()) {
599 throw new IllegalStateException("VPN is not active");
600 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700601
Paul Jensen0784eea2014-08-19 16:00:24 -0400602 if (mConfig.allowedApplications != null) {
603 // Add ranges covering all UIDs for allowedApplications.
604 int start = -1, stop = -1;
605 for (int uid : getAppsUids(mConfig.allowedApplications, userHandle)) {
606 if (start == -1) {
607 start = uid;
608 } else if (uid != stop + 1) {
609 mVpnUsers.add(new UidRange(start, stop));
610 start = uid;
611 }
612 stop = uid;
613 }
614 if (start != -1) mVpnUsers.add(new UidRange(start, stop));
615 } else if (mConfig.disallowedApplications != null) {
616 // Add all ranges for user skipping UIDs for disallowedApplications.
617 final UidRange userRange = UidRange.createForUser(userHandle);
618 int start = userRange.start;
619 for (int uid : getAppsUids(mConfig.disallowedApplications, userHandle)) {
620 if (uid == start) {
621 start++;
622 } else {
623 mVpnUsers.add(new UidRange(start, uid - 1));
624 start = uid + 1;
625 }
626 }
627 if (start <= userRange.stop) mVpnUsers.add(new UidRange(start, userRange.stop));
628 } else {
629 // Add all UIDs for the user.
630 mVpnUsers.add(UidRange.createForUser(userHandle));
631 }
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700632
633 prepareStatusIntent();
Chad Brubakerc2865192013-07-10 14:46:23 -0700634 }
635
Paul Jensen0784eea2014-08-19 16:00:24 -0400636 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
637 // apply to userHandle.
638 private List<UidRange> uidRangesForUser(int userHandle) {
639 final UidRange userRange = UidRange.createForUser(userHandle);
640 final List<UidRange> ranges = new ArrayList<UidRange>();
641 for (UidRange range : mVpnUsers) {
642 if (range.start >= userRange.start && range.stop <= userRange.stop) {
643 ranges.add(range);
644 }
645 }
646 return ranges;
647 }
648
649 private void removeVpnUserLocked(int userHandle) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700650 if (!isRunningLocked()) {
651 throw new IllegalStateException("VPN is not active");
652 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400653 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700654 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400655 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700656 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400657 mVpnUsers.removeAll(ranges);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700658 mStatusIntent = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700659 }
660
Paul Jensen0784eea2014-08-19 16:00:24 -0400661 private void onUserAdded(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700662 // If the user is restricted tie them to the owner's VPN
663 synchronized(Vpn.this) {
664 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400665 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700666 if (user.isRestricted()) {
667 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400668 addVpnUserLocked(userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400669 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400670 final List<UidRange> ranges = uidRangesForUser(userHandle);
671 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400672 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700673 } catch (Exception e) {
674 Log.wtf(TAG, "Failed to add restricted user to owner", e);
675 }
676 }
677 }
678 }
679
Paul Jensen0784eea2014-08-19 16:00:24 -0400680 private void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700681 // clean up if restricted
682 synchronized(Vpn.this) {
683 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400684 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700685 if (user.isRestricted()) {
686 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400687 removeVpnUserLocked(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700688 } catch (Exception e) {
689 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
690 }
691 }
692 }
693 }
694
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700695 /**
696 * Return the configuration of the currently running VPN.
697 */
698 public VpnConfig getVpnConfig() {
699 enforceControlPermission();
700 return mConfig;
701 }
702
Jeff Sharkey899223b2012-08-04 15:24:58 -0700703 @Deprecated
704 public synchronized void interfaceStatusChanged(String iface, boolean up) {
705 try {
706 mObserver.interfaceStatusChanged(iface, up);
707 } catch (RemoteException e) {
708 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700709 }
710 }
711
Jeff Sharkey899223b2012-08-04 15:24:58 -0700712 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
713 @Override
714 public void interfaceStatusChanged(String interfaze, boolean up) {
715 synchronized (Vpn.this) {
716 if (!up && mLegacyVpnRunner != null) {
717 mLegacyVpnRunner.check(interfaze);
718 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700719 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700720 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700721
Jeff Sharkey899223b2012-08-04 15:24:58 -0700722 @Override
723 public void interfaceRemoved(String interfaze) {
724 synchronized (Vpn.this) {
725 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700726 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400727 mVpnUsers = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700728 mInterface = null;
729 if (mConnection != null) {
730 mContext.unbindService(mConnection);
731 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400732 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700733 } else if (mLegacyVpnRunner != null) {
734 mLegacyVpnRunner.exit();
735 mLegacyVpnRunner = null;
736 }
737 }
738 }
739 }
740 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700741
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700742 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -0800743 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700744 }
745
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700746 private class Connection implements ServiceConnection {
747 private IBinder mService;
748
749 @Override
750 public void onServiceConnected(ComponentName name, IBinder service) {
751 mService = service;
752 }
753
754 @Override
755 public void onServiceDisconnected(ComponentName name) {
756 mService = null;
757 }
758 }
759
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700760 private void prepareStatusIntent() {
761 final long token = Binder.clearCallingIdentity();
762 try {
763 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
764 } finally {
765 Binder.restoreCallingIdentity(token);
766 }
767 }
768
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700769 public synchronized boolean addAddress(String address, int prefixLength) {
770 if (Binder.getCallingUid() != mOwnerUID || mInterface == null || mNetworkAgent == null) {
771 return false;
772 }
773 boolean success = jniAddAddress(mInterface, address, prefixLength);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900774 if (mNetworkAgent != null) {
775 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700776 }
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700777 return success;
778 }
779
780 public synchronized boolean removeAddress(String address, int prefixLength) {
781 if (Binder.getCallingUid() != mOwnerUID || mInterface == null || mNetworkAgent == null) {
782 return false;
783 }
784 boolean success = jniDelAddress(mInterface, address, prefixLength);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900785 if (mNetworkAgent != null) {
786 mNetworkAgent.sendLinkProperties(makeLinkProperties());
787 }
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700788 return success;
789 }
790
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700791 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700792 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700793 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700794 private native void jniReset(String interfaze);
795 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700796 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
797 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700798
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900799 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
800 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700801 // Currently legacy VPN only works on IPv4.
802 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900803 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700804 }
805 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700806
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900807 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700808 }
809
810 /**
811 * Start legacy VPN, controlling native daemons as needed. Creates a
812 * secondary thread to perform connection work, returning quickly.
813 */
814 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800815 enforceControlPermission();
Kenny Rootb9594ce2013-02-14 10:18:38 -0800816 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700817 throw new IllegalStateException("KeyStore isn't unlocked");
818 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400819 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400820 UserInfo user = mgr.getUserInfo(mUserHandle);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400821 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
822 throw new SecurityException("Restricted users cannot establish VPNs");
823 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700824
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900825 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
826 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
827 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700828
829 // Load certificates.
830 String privateKey = "";
831 String userCert = "";
832 String caCert = "";
833 String serverCert = "";
834 if (!profile.ipsecUserCert.isEmpty()) {
835 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
836 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700837 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700838 }
839 if (!profile.ipsecCaCert.isEmpty()) {
840 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700841 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700842 }
843 if (!profile.ipsecServerCert.isEmpty()) {
844 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700845 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700846 }
847 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
848 throw new IllegalStateException("Cannot load credentials");
849 }
850
851 // Prepare arguments for racoon.
852 String[] racoon = null;
853 switch (profile.type) {
854 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
855 racoon = new String[] {
856 iface, profile.server, "udppsk", profile.ipsecIdentifier,
857 profile.ipsecSecret, "1701",
858 };
859 break;
860 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
861 racoon = new String[] {
862 iface, profile.server, "udprsa", privateKey, userCert,
863 caCert, serverCert, "1701",
864 };
865 break;
866 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
867 racoon = new String[] {
868 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
869 profile.ipsecSecret, profile.username, profile.password, "", gateway,
870 };
871 break;
872 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
873 racoon = new String[] {
874 iface, profile.server, "xauthrsa", privateKey, userCert,
875 caCert, serverCert, profile.username, profile.password, "", gateway,
876 };
877 break;
878 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
879 racoon = new String[] {
880 iface, profile.server, "hybridrsa",
881 caCert, serverCert, profile.username, profile.password, "", gateway,
882 };
883 break;
884 }
885
886 // Prepare arguments for mtpd.
887 String[] mtpd = null;
888 switch (profile.type) {
889 case VpnProfile.TYPE_PPTP:
890 mtpd = new String[] {
891 iface, "pptp", profile.server, "1723",
892 "name", profile.username, "password", profile.password,
893 "linkname", "vpn", "refuse-eap", "nodefaultroute",
894 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
895 (profile.mppe ? "+mppe" : "nomppe"),
896 };
897 break;
898 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
899 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
900 mtpd = new String[] {
901 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
902 "name", profile.username, "password", profile.password,
903 "linkname", "vpn", "refuse-eap", "nodefaultroute",
904 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
905 };
906 break;
907 }
908
909 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700910 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700911 config.user = profile.key;
912 config.interfaze = iface;
913 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700914
915 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700916 if (!profile.dnsServers.isEmpty()) {
917 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
918 }
919 if (!profile.searchDomains.isEmpty()) {
920 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
921 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700922 startLegacyVpn(config, racoon, mtpd);
923 }
924
925 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
926 stopLegacyVpn();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700927
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700928 // Prepare for the new request. This also checks the caller.
929 prepare(null, VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700930 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700931
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700932 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700933 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
934 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700935 }
936
Jeff Sharkey899223b2012-08-04 15:24:58 -0700937 public synchronized void stopLegacyVpn() {
938 if (mLegacyVpnRunner != null) {
939 mLegacyVpnRunner.exit();
940 mLegacyVpnRunner = null;
941
942 synchronized (LegacyVpnRunner.TAG) {
943 // wait for old thread to completely finish before spinning up
944 // new instance, otherwise state updates can be out of order.
945 }
946 }
947 }
948
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700949 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700950 * Return the information of the current ongoing legacy VPN.
951 */
952 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700953 // Check if the caller is authorized.
954 enforceControlPermission();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700955 if (mLegacyVpnRunner == null) return null;
956
957 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -0700958 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700959 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700960 if (mNetworkInfo.isConnected()) {
961 info.intent = mStatusIntent;
962 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700963 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700964 }
965
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700966 public VpnConfig getLegacyVpnConfig() {
967 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700968 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700969 } else {
970 return null;
971 }
972 }
973
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700974 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700975 * Bringing up a VPN connection takes time, and that is all this thread
976 * does. Here we have plenty of time. The only thing we need to take
977 * care of is responding to interruptions as soon as possible. Otherwise
978 * requests will be piled up. This can be done in a Handler as a state
979 * machine, but it is much easier to read in the current form.
980 */
981 private class LegacyVpnRunner extends Thread {
982 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700983
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700984 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700985 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700986 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700987 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700988 private final AtomicInteger mOuterConnection =
989 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700990
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700991 private long mTimer = -1;
992
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700993 /**
994 * Watch for the outer connection (passing in the constructor) going away.
995 */
996 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
997 @Override
998 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -0700999 if (!mEnableTeardown) return;
1000
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001001 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1002 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1003 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1004 NetworkInfo info = (NetworkInfo)intent.getExtra(
1005 ConnectivityManager.EXTRA_NETWORK_INFO);
1006 if (info != null && !info.isConnectedOrConnecting()) {
1007 try {
1008 mObserver.interfaceStatusChanged(mOuterInterface, false);
1009 } catch (RemoteException e) {}
1010 }
1011 }
1012 }
1013 }
1014 };
1015
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001016 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001017 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001018 mConfig = config;
1019 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001020 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001021 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001022 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001023
1024 // This is the interface which VPN is running on,
1025 // mConfig.interfaze will change to point to OUR
1026 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001027 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001028 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001029 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001030 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001031
1032 try {
1033 mOuterConnection.set(
1034 mConnService.findConnectionTypeForIface(mOuterInterface));
1035 } catch (Exception e) {
1036 mOuterConnection.set(ConnectivityManager.TYPE_NONE);
1037 }
1038
1039 IntentFilter filter = new IntentFilter();
1040 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1041 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001042 }
1043
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001044 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001045 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001046 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1047 exit();
1048 }
1049 }
1050
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001051 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001052 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001053 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001054 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001055 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001056 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001057 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001058 try {
1059 mContext.unregisterReceiver(mBroadcastReceiver);
1060 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001061 }
1062
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001063 @Override
1064 public void run() {
1065 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001066 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001067 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001068 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001069 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001070 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001071 }
1072 }
1073
1074 private void checkpoint(boolean yield) throws InterruptedException {
1075 long now = SystemClock.elapsedRealtime();
1076 if (mTimer == -1) {
1077 mTimer = now;
1078 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001079 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001080 Thread.sleep(yield ? 200 : 1);
1081 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001082 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001083 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001084 }
1085 }
1086
1087 private void execute() {
1088 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001089 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001090 try {
1091 // Initialize the timer.
1092 checkpoint(false);
1093
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001094 // Wait for the daemons to stop.
1095 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001096 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001097 checkpoint(true);
1098 }
1099 }
1100
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001101 // Clear the previous state.
1102 File state = new File("/data/misc/vpn/state");
1103 state.delete();
1104 if (state.exists()) {
1105 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001106 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001107 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001108 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001109
Chia-chi Yehe9107902011-07-02 01:48:50 -07001110 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001111 boolean restart = false;
1112 for (String[] arguments : mArguments) {
1113 restart = restart || (arguments != null);
1114 }
1115 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001116 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001117 return;
1118 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001119 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001120
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001121 // Start the daemon with arguments.
1122 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001123 String[] arguments = mArguments[i];
1124 if (arguments == null) {
1125 continue;
1126 }
1127
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001128 // Start the daemon.
1129 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001130 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001131
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001132 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001133 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001134 checkpoint(true);
1135 }
1136
1137 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001138 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001139 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001140 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001141
1142 // Wait for the socket to connect.
1143 while (true) {
1144 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001145 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001146 break;
1147 } catch (Exception e) {
1148 // ignore
1149 }
1150 checkpoint(true);
1151 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001152 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001153
1154 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001155 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001156 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001157 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001158 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001159 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001160 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001161 out.write(bytes.length >> 8);
1162 out.write(bytes.length);
1163 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001164 checkpoint(false);
1165 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001166 out.write(0xFF);
1167 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001168 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001169
1170 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001171 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001172 while (true) {
1173 try {
1174 if (in.read() == -1) {
1175 break;
1176 }
1177 } catch (Exception e) {
1178 // ignore
1179 }
1180 checkpoint(true);
1181 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001182 }
1183
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001184 // Wait for the daemons to create the new state.
1185 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001186 // Check if a running daemon is dead.
1187 for (int i = 0; i < mDaemons.length; ++i) {
1188 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001189 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001190 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001191 }
1192 }
1193 checkpoint(true);
1194 }
1195
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001196 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001197 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001198 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001199 throw new IllegalStateException("Cannot parse the state");
1200 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001201
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001202 // Set the interface and the addresses in the config.
1203 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001204
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001205 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001206 // Set the routes if they are not set in the config.
1207 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001208 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001209 }
1210
1211 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001212 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001213 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001214 if (!dnsServers.isEmpty()) {
1215 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1216 }
1217 }
1218
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001219 // Set the search domains if they are not set in the config.
1220 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1221 String searchDomains = parameters[4].trim();
1222 if (!searchDomains.isEmpty()) {
1223 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1224 }
1225 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001226
Lorenzo Colitti50262792014-09-19 01:53:35 +09001227 // Add a throw route for the VPN server endpoint, if one was specified.
1228 String endpoint = parameters[5];
1229 if (!endpoint.isEmpty()) {
1230 try {
1231 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1232 if (addr instanceof Inet4Address) {
1233 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1234 } else if (addr instanceof Inet6Address) {
1235 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1236 } else {
1237 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1238 }
1239 } catch (IllegalArgumentException e) {
1240 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1241 }
1242 }
1243
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001244 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001245 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001246 // Set the start time
1247 mConfig.startTime = SystemClock.elapsedRealtime();
1248
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001249 // Check if the thread is interrupted while we are waiting.
1250 checkpoint(false);
1251
Chia-chi Yehe9107902011-07-02 01:48:50 -07001252 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001253 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001254 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001255 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001256
1257 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001258 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001259 mVpnUsers = new ArrayList<UidRange>();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001260
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001261 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001262
1263 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001264 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001265 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001266 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001267 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001268 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001269 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001270 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001271 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001272 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001273 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001274 }
1275 }
1276
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001277 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001278 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001279 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001280 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001281 }
1282 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001283
1284 /**
1285 * Monitor the daemons we started, moving to disconnected state if the
1286 * underlying services fail.
1287 */
1288 private void monitorDaemons() {
1289 if (!mNetworkInfo.isConnected()) {
1290 return;
1291 }
1292
1293 try {
1294 while (true) {
1295 Thread.sleep(2000);
1296 for (int i = 0; i < mDaemons.length; i++) {
1297 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1298 return;
1299 }
1300 }
1301 }
1302 } catch (InterruptedException e) {
1303 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1304 } finally {
1305 for (String daemon : mDaemons) {
1306 SystemService.stop(daemon);
1307 }
1308
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001309 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001310 }
1311 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001312 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001313}