blob: b9dd609207fca10dff77f65f89daffca2aa3344e [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;
Jeff Sharkey82f85212012-08-24 11:17:25 -070086import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -070087import java.net.Inet6Address;
88import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070089import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040090import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070091import java.util.Arrays;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040092import java.util.List;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070093import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070094
Jeff Sharkey065b2992012-08-05 14:16:48 -070095import libcore.io.IoUtils;
96
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070097/**
98 * @hide
99 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400100public class Vpn {
101 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700102 private static final String TAG = "Vpn";
103 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400104
Jeff Sharkey899223b2012-08-04 15:24:58 -0700105 // TODO: create separate trackers for each unique VPN to support
106 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700107
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400108 private Context mContext;
109 private NetworkInfo mNetworkInfo;
110 private String mPackage;
111 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700112 private String mInterface;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700113 private boolean mAllowIPv4;
114 private boolean mAllowIPv6;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700115 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700116 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700117 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700118 private volatile boolean mEnableNotif = true;
119 private volatile boolean mEnableTeardown = true;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700120 private final IConnectivityManager mConnService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400121 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700122 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400123 private NetworkAgent mNetworkAgent;
124 private final Looper mLooper;
125 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700126
127 /* list of users using this VPN. */
128 @GuardedBy("this")
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400129 private List<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700130 private BroadcastReceiver mUserIntentReceiver = null;
131
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700132 private final int mUserId;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700133
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400134 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700135 IConnectivityManager connService, int userId) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700136 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400137 mNetd = netService;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700138 mConnService = connService;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700139 mUserId = userId;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400140 mLooper = looper;
141
142 mPackage = VpnConfig.LEGACY_VPN;
143 mOwnerUID = getAppUid(mPackage);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700144
145 try {
146 netService.registerObserver(mObserver);
147 } catch (RemoteException e) {
148 Log.wtf(TAG, "Problem registering observer", e);
149 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700150 if (userId == UserHandle.USER_OWNER) {
151 // Owner's VPN also needs to handle restricted users
152 mUserIntentReceiver = new BroadcastReceiver() {
153 @Override
154 public void onReceive(Context context, Intent intent) {
155 final String action = intent.getAction();
156 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
157 UserHandle.USER_NULL);
158 if (userId == UserHandle.USER_NULL) return;
159
160 if (Intent.ACTION_USER_ADDED.equals(action)) {
161 onUserAdded(userId);
162 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
163 onUserRemoved(userId);
164 }
165 }
166 };
167
168 IntentFilter intentFilter = new IntentFilter();
169 intentFilter.addAction(Intent.ACTION_USER_ADDED);
170 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
171 mContext.registerReceiverAsUser(
172 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
173 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400174
175 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
176 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
177 mNetworkCapabilities = new NetworkCapabilities();
178 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
179 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700180 }
181
Jeff Sharkey57666932013-04-30 17:01:57 -0700182 /**
183 * Set if this object is responsible for showing its own notifications. When
184 * {@code false}, notifications are handled externally by someone else.
185 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700186 public void setEnableNotifications(boolean enableNotif) {
187 mEnableNotif = enableNotif;
188 }
189
Jeff Sharkey57666932013-04-30 17:01:57 -0700190 /**
191 * Set if this object is responsible for watching for {@link NetworkInfo}
192 * teardown. When {@code false}, teardown is handled externally by someone
193 * else.
194 */
195 public void setEnableTeardown(boolean enableTeardown) {
196 mEnableTeardown = enableTeardown;
197 }
198
Jeff Sharkey899223b2012-08-04 15:24:58 -0700199 /**
200 * Update current state, dispaching event to listeners.
201 */
202 private void updateState(DetailedState detailedState, String reason) {
203 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
204 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400205 if (mNetworkAgent != null) {
206 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
207 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700208 }
209
210 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700211 * Prepare for a VPN application. This method is designed to solve
212 * race conditions. It first compares the current prepared package
213 * with {@code oldPackage}. If they are the same, the prepared
214 * package is revoked and replaced with {@code newPackage}. If
215 * {@code oldPackage} is {@code null}, the comparison is omitted.
216 * If {@code newPackage} is the same package or {@code null}, the
217 * revocation is omitted. This method returns {@code true} if the
218 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700219 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700220 * Legacy VPN is handled specially since it is not a real package.
221 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
222 * it can be revoked by itself.
223 *
224 * @param oldPackage The package name of the old VPN application.
225 * @param newPackage The package name of the new VPN application.
226 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700227 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700228 public synchronized boolean prepare(String oldPackage, String newPackage) {
229 // Return false if the package does not match.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700230 if (oldPackage != null && !oldPackage.equals(mPackage)) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700231 return false;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700232 }
233
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700234 // Return true if we do not need to revoke.
235 if (newPackage == null ||
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700236 (newPackage.equals(mPackage) && !newPackage.equals(VpnConfig.LEGACY_VPN))) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700237 return true;
238 }
239
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700240 // Check if the caller is authorized.
241 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700242
Chia-chi Yehe9107902011-07-02 01:48:50 -0700243 // Reset the interface and hide the notification.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700244 if (mInterface != null) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400245 for (UidRange uidRange : mVpnUsers) {
246 hideNotification(uidRange.getStartUser());
Jeff Sharkey899223b2012-08-04 15:24:58 -0700247 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400248 agentDisconnect();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700249 jniReset(mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700250 mInterface = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700251 mVpnUsers = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700252 }
253
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700254 // Revoke the connection or stop LegacyVpnRunner.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700255 if (mConnection != null) {
256 try {
257 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
258 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
259 } catch (Exception e) {
260 // ignore
261 }
262 mContext.unbindService(mConnection);
263 mConnection = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700264 } else if (mLegacyVpnRunner != null) {
265 mLegacyVpnRunner.exit();
266 mLegacyVpnRunner = null;
267 }
268
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400269 long token = Binder.clearCallingIdentity();
270 try {
271 mNetd.denyProtect(mOwnerUID);
272 } catch (Exception e) {
273 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
274 } finally {
275 Binder.restoreCallingIdentity(token);
276 }
277
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700278 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
279 mPackage = newPackage;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400280 mOwnerUID = getAppUid(newPackage);
281 token = Binder.clearCallingIdentity();
282 try {
283 mNetd.allowProtect(mOwnerUID);
284 } catch (Exception e) {
285 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
286 } finally {
287 Binder.restoreCallingIdentity(token);
288 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700289 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700290 updateState(DetailedState.IDLE, "prepare");
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700291 return true;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700292 }
293
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400294 private int getAppUid(String app) {
295 if (app == VpnConfig.LEGACY_VPN) {
296 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700297 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400298 PackageManager pm = mContext.getPackageManager();
299 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700300 try {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400301 result = pm.getPackageUid(app, mUserId);
302 } catch (NameNotFoundException e) {
303 result = -1;
304 }
305 return result;
306 }
307
308 public NetworkInfo getNetworkInfo() {
309 return mNetworkInfo;
310 }
311
312 private void agentConnect() {
313 LinkProperties lp = new LinkProperties();
314 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700315
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400316 boolean hasDefaultRoute = false;
317 for (RouteInfo route : mConfig.routes) {
318 lp.addRoute(route);
319 if (route.isDefaultRoute()) hasDefaultRoute = true;
320 }
321 if (hasDefaultRoute) {
322 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
323 } else {
324 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
325 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700326
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400327 if (mConfig.dnsServers != null) {
328 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700329 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
330 lp.addDnsServer(address);
331 if (address instanceof Inet4Address) {
332 mAllowIPv4 = true;
333 } else {
334 mAllowIPv6 = true;
335 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400336 }
337 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700338
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400339 // Concatenate search domains into a string.
340 StringBuilder buffer = new StringBuilder();
341 if (mConfig.searchDomains != null) {
342 for (String domain : mConfig.searchDomains) {
343 buffer.append(domain).append(' ');
344 }
345 }
346 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700347
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400348 mNetworkInfo.setIsAvailable(true);
349 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700350
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700351 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700352 networkMisc.allowBypass = mConfig.allowBypass;
353
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400354 long token = Binder.clearCallingIdentity();
355 try {
356 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700357 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400358 public void unwanted() {
359 // We are user controlled, not driven by NetworkRequest.
360 };
361 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700362 } finally {
363 Binder.restoreCallingIdentity(token);
364 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700365
366 if (!mAllowIPv4) {
367 mNetworkAgent.blockAddressFamily(AF_INET);
368 }
369 if (!mAllowIPv6) {
370 mNetworkAgent.blockAddressFamily(AF_INET6);
371 }
372
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400373 addVpnUserLocked(mUserId);
374 // If we are owner assign all Restricted Users to this VPN
375 if (mUserId == UserHandle.USER_OWNER) {
376 token = Binder.clearCallingIdentity();
377 List<UserInfo> users;
378 try {
379 users = UserManager.get(mContext).getUsers();
380 } finally {
381 Binder.restoreCallingIdentity(token);
382 }
383 for (UserInfo user : users) {
384 if (user.isRestricted()) {
385 addVpnUserLocked(user.id);
386 }
387 }
388 }
389 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
390 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700391
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400392 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
393 networkInfo.setIsAvailable(false);
394 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
395 if (networkAgent != null) {
396 networkAgent.sendNetworkInfo(networkInfo);
397 }
398 }
399
400 private void agentDisconnect(NetworkAgent networkAgent) {
401 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
402 agentDisconnect(networkInfo, networkAgent);
403 }
404
405 private void agentDisconnect() {
406 if (mNetworkInfo.isConnected()) {
407 agentDisconnect(mNetworkInfo, mNetworkAgent);
408 mNetworkAgent = null;
409 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700410 }
411
412 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700413 * Establish a VPN network and return the file descriptor of the VPN
414 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700415 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700416 *
417 * @param config The parameters to configure the network.
418 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700419 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700420 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700421 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700422 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400423 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700424 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700425 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700426 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700427 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
428 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700429 long token = Binder.clearCallingIdentity();
430 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700431 // Restricted users are not allowed to create VPNs, they are tied to Owner
432 UserInfo user = mgr.getUserInfo(mUserId);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400433 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700434 throw new SecurityException("Restricted users cannot establish VPNs");
435 }
436
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700437 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
438 null, 0, mUserId);
439 if (info == null) {
440 throw new SecurityException("Cannot find " + config.user);
441 }
442 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
443 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
444 }
445 } catch (RemoteException e) {
446 throw new SecurityException("Cannot find " + config.user);
447 } finally {
448 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700449 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700450
Chad Brubaker850eb672014-03-21 21:02:47 +0000451 // Save the old config in case we need to go back.
452 VpnConfig oldConfig = mConfig;
453 String oldInterface = mInterface;
454 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400455 NetworkAgent oldNetworkAgent = mNetworkAgent;
456 mNetworkAgent = null;
457 List<UidRange> oldUsers = mVpnUsers;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700458 boolean oldAllowIPv4 = mAllowIPv4;
459 boolean oldAllowIPv6 = mAllowIPv6;
Chad Brubaker850eb672014-03-21 21:02:47 +0000460
Chia-chi Yehe9107902011-07-02 01:48:50 -0700461 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700462 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700463 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700464 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700465 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700466
Chad Brubakerc2865192013-07-10 14:46:23 -0700467 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700468 StringBuilder builder = new StringBuilder();
469 for (LinkAddress address : config.addresses) {
470 builder.append(" " + address);
471 }
472 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700473 throw new IllegalArgumentException("At least one address must be specified");
474 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700475 Connection connection = new Connection();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700476 if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
477 new UserHandle(mUserId))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700478 throw new IllegalStateException("Cannot bind " + config.user);
479 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000480
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700481 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700482 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700483
484 // Fill more values.
485 config.user = mPackage;
486 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700487 config.startTime = SystemClock.elapsedRealtime();
488 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000489
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700490 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400491 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700492 mAllowIPv4 = mConfig.allowIPv4;
493 mAllowIPv6 = mConfig.allowIPv6;
494
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400495 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000496
497 if (oldConnection != null) {
498 mContext.unbindService(oldConnection);
499 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400500 // Remove the old tun's user forwarding rules
501 // The new tun's user rules have already been added so they will take over
502 // as rules are deleted. This prevents data leakage as the rules are moved over.
503 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000504 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000505 jniReset(oldInterface);
506 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700507
508 try {
509 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
510 } catch (IOException e) {
511 throw new IllegalStateException(
512 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
513 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000514 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000515 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400516 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000517 // restore old state
518 mConfig = oldConfig;
519 mConnection = oldConnection;
520 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400521 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000522 mInterface = oldInterface;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700523 mAllowIPv4 = oldAllowIPv4;
524 mAllowIPv6 = oldAllowIPv6;
Chad Brubaker850eb672014-03-21 21:02:47 +0000525 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700526 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000527 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700528 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700529 }
530
Chad Brubakerc2865192013-07-10 14:46:23 -0700531 private boolean isRunningLocked() {
532 return mVpnUsers != null;
533 }
534
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400535 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Chad Brubakerc2865192013-07-10 14:46:23 -0700536 private void addVpnUserLocked(int user) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700537 if (!isRunningLocked()) {
538 throw new IllegalStateException("VPN is not active");
539 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700540
Chad Brubakerc2865192013-07-10 14:46:23 -0700541 // add the user
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400542 mVpnUsers.add(UidRange.createForUser(user));
Chad Brubakerc2865192013-07-10 14:46:23 -0700543
544 // show the notification
545 if (!mPackage.equals(VpnConfig.LEGACY_VPN)) {
546 // Load everything for the user's notification
547 PackageManager pm = mContext.getPackageManager();
548 ApplicationInfo app = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400549 final long token = Binder.clearCallingIdentity();
Chad Brubakerc2865192013-07-10 14:46:23 -0700550 try {
551 app = AppGlobals.getPackageManager().getApplicationInfo(mPackage, 0, mUserId);
552 } catch (RemoteException e) {
553 throw new IllegalStateException("Invalid application");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400554 } finally {
555 Binder.restoreCallingIdentity(token);
Chad Brubakerc2865192013-07-10 14:46:23 -0700556 }
557 String label = app.loadLabel(pm).toString();
558 // Load the icon and convert it into a bitmap.
559 Drawable icon = app.loadIcon(pm);
560 Bitmap bitmap = null;
561 if (icon.getIntrinsicWidth() > 0 && icon.getIntrinsicHeight() > 0) {
562 int width = mContext.getResources().getDimensionPixelSize(
563 android.R.dimen.notification_large_icon_width);
564 int height = mContext.getResources().getDimensionPixelSize(
565 android.R.dimen.notification_large_icon_height);
566 icon.setBounds(0, 0, width, height);
567 bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
568 Canvas c = new Canvas(bitmap);
569 icon.draw(c);
570 c.setBitmap(null);
571 }
572 showNotification(label, bitmap, user);
573 } else {
574 showNotification(null, null, user);
575 }
576 }
577
578 private void removeVpnUserLocked(int user) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700579 if (!isRunningLocked()) {
580 throw new IllegalStateException("VPN is not active");
581 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400582 UidRange uidRange = UidRange.createForUser(user);
583 if (mNetworkAgent != null) {
584 mNetworkAgent.removeUidRanges(new UidRange[] { uidRange });
585 }
586 mVpnUsers.remove(uidRange);
Chad Brubakerc2865192013-07-10 14:46:23 -0700587 hideNotification(user);
588 }
589
590 private void onUserAdded(int userId) {
591 // If the user is restricted tie them to the owner's VPN
592 synchronized(Vpn.this) {
593 UserManager mgr = UserManager.get(mContext);
594 UserInfo user = mgr.getUserInfo(userId);
595 if (user.isRestricted()) {
596 try {
597 addVpnUserLocked(userId);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400598 if (mNetworkAgent != null) {
599 UidRange uidRange = UidRange.createForUser(userId);
600 mNetworkAgent.addUidRanges(new UidRange[] { uidRange });
601 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700602 } catch (Exception e) {
603 Log.wtf(TAG, "Failed to add restricted user to owner", e);
604 }
605 }
606 }
607 }
608
609 private void onUserRemoved(int userId) {
610 // clean up if restricted
611 synchronized(Vpn.this) {
612 UserManager mgr = UserManager.get(mContext);
613 UserInfo user = mgr.getUserInfo(userId);
614 if (user.isRestricted()) {
615 try {
616 removeVpnUserLocked(userId);
617 } catch (Exception e) {
618 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
619 }
620 }
621 }
622 }
623
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700624 /**
625 * Return the configuration of the currently running VPN.
626 */
627 public VpnConfig getVpnConfig() {
628 enforceControlPermission();
629 return mConfig;
630 }
631
Jeff Sharkey899223b2012-08-04 15:24:58 -0700632 @Deprecated
633 public synchronized void interfaceStatusChanged(String iface, boolean up) {
634 try {
635 mObserver.interfaceStatusChanged(iface, up);
636 } catch (RemoteException e) {
637 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700638 }
639 }
640
Jeff Sharkey899223b2012-08-04 15:24:58 -0700641 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
642 @Override
643 public void interfaceStatusChanged(String interfaze, boolean up) {
644 synchronized (Vpn.this) {
645 if (!up && mLegacyVpnRunner != null) {
646 mLegacyVpnRunner.check(interfaze);
647 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700648 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700649 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700650
Jeff Sharkey899223b2012-08-04 15:24:58 -0700651 @Override
652 public void interfaceRemoved(String interfaze) {
653 synchronized (Vpn.this) {
654 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400655 for (UidRange uidRange : mVpnUsers) {
656 hideNotification(uidRange.getStartUser());
Jeff Sharkey899223b2012-08-04 15:24:58 -0700657 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400658 mVpnUsers = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700659 mInterface = null;
660 if (mConnection != null) {
661 mContext.unbindService(mConnection);
662 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400663 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700664 } else if (mLegacyVpnRunner != null) {
665 mLegacyVpnRunner.exit();
666 mLegacyVpnRunner = null;
667 }
668 }
669 }
670 }
671 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700672
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700673 private void enforceControlPermission() {
674 // System user is allowed to control VPN.
675 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
676 return;
677 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700678 int appId = UserHandle.getAppId(Binder.getCallingUid());
679 final long token = Binder.clearCallingIdentity();
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700680 try {
Nick Kralevich212a1952013-10-18 17:48:39 -0700681 // System VPN dialogs are also allowed to control VPN.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700682 PackageManager pm = mContext.getPackageManager();
683 ApplicationInfo app = pm.getApplicationInfo(VpnConfig.DIALOGS_PACKAGE, 0);
Nick Kralevich212a1952013-10-18 17:48:39 -0700684 if (((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) && (appId == app.uid)) {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700685 return;
686 }
687 } catch (Exception e) {
688 // ignore
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700689 } finally {
690 Binder.restoreCallingIdentity(token);
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700691 }
692
693 throw new SecurityException("Unauthorized Caller");
694 }
695
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700696 private class Connection implements ServiceConnection {
697 private IBinder mService;
698
699 @Override
700 public void onServiceConnected(ComponentName name, IBinder service) {
701 mService = service;
702 }
703
704 @Override
705 public void onServiceDisconnected(ComponentName name) {
706 mService = null;
707 }
708 }
709
Chad Brubakerc2865192013-07-10 14:46:23 -0700710 private void showNotification(String label, Bitmap icon, int user) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700711 if (!mEnableNotif) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400712 final long token = Binder.clearCallingIdentity();
713 try {
714 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700715
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400716 NotificationManager nm = (NotificationManager)
717 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700718
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400719 if (nm != null) {
720 String title = (label == null) ? mContext.getString(R.string.vpn_title) :
721 mContext.getString(R.string.vpn_title_long, label);
722 String text = (mConfig.session == null) ? mContext.getString(R.string.vpn_text) :
723 mContext.getString(R.string.vpn_text_long, mConfig.session);
Chia-chi Yeha4b87b52011-06-30 23:21:55 -0700724
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400725 Notification notification = new Notification.Builder(mContext)
726 .setSmallIcon(R.drawable.vpn_connected)
727 .setLargeIcon(icon)
728 .setContentTitle(title)
729 .setContentText(text)
730 .setContentIntent(mStatusIntent)
731 .setDefaults(0)
732 .setOngoing(true)
733 .build();
734 nm.notifyAsUser(null, R.drawable.vpn_connected, notification, new UserHandle(user));
735 }
736 } finally {
737 Binder.restoreCallingIdentity(token);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700738 }
739 }
740
Chad Brubakerc2865192013-07-10 14:46:23 -0700741 private void hideNotification(int user) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700742 if (!mEnableNotif) return;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700743 mStatusIntent = null;
744
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700745 NotificationManager nm = (NotificationManager)
746 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
747
748 if (nm != null) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400749 final long token = Binder.clearCallingIdentity();
750 try {
751 nm.cancelAsUser(null, R.drawable.vpn_connected, new UserHandle(user));
752 } finally {
753 Binder.restoreCallingIdentity(token);
754 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700755 }
756 }
757
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700758 public synchronized boolean addAddress(String address, int prefixLength) {
759 if (Binder.getCallingUid() != mOwnerUID || mInterface == null || mNetworkAgent == null) {
760 return false;
761 }
762 boolean success = jniAddAddress(mInterface, address, prefixLength);
763 if (success && (!mAllowIPv4 || !mAllowIPv6)) {
764 try {
765 InetAddress inetAddress = InetAddress.parseNumericAddress(address);
766 if ((inetAddress instanceof Inet4Address) && !mAllowIPv4) {
767 mAllowIPv4 = true;
768 mNetworkAgent.unblockAddressFamily(AF_INET);
769 } else if ((inetAddress instanceof Inet6Address) && !mAllowIPv6) {
770 mAllowIPv6 = true;
771 mNetworkAgent.unblockAddressFamily(AF_INET6);
772 }
773 } catch (IllegalArgumentException e) {
774 // ignore
775 }
776 }
777 // Ideally, we'd call mNetworkAgent.sendLinkProperties() here to notify ConnectivityService
778 // that the LinkAddress has changed. But we don't do so for two reasons: (1) We don't set
779 // LinkAddresses on the LinkProperties we establish in the first place (see agentConnect())
780 // and (2) CS doesn't do anything with LinkAddresses anyway (see updateLinkProperties()).
781 // TODO: Maybe fix this.
782 return success;
783 }
784
785 public synchronized boolean removeAddress(String address, int prefixLength) {
786 if (Binder.getCallingUid() != mOwnerUID || mInterface == null || mNetworkAgent == null) {
787 return false;
788 }
789 boolean success = jniDelAddress(mInterface, address, prefixLength);
790 // Ideally, we'd call mNetworkAgent.sendLinkProperties() here to notify ConnectivityService
791 // that the LinkAddress has changed. But we don't do so for two reasons: (1) We don't set
792 // LinkAddresses on the LinkProperties we establish in the first place (see agentConnect())
793 // and (2) CS doesn't do anything with LinkAddresses anyway (see updateLinkProperties()).
794 // TODO: Maybe fix this.
795 return success;
796 }
797
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700798 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700799 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700800 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700801 private native void jniReset(String interfaze);
802 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700803 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
804 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700805
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900806 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
807 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700808 // Currently legacy VPN only works on IPv4.
809 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900810 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700811 }
812 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700813
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900814 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700815 }
816
817 /**
818 * Start legacy VPN, controlling native daemons as needed. Creates a
819 * secondary thread to perform connection work, returning quickly.
820 */
821 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800822 enforceControlPermission();
Kenny Rootb9594ce2013-02-14 10:18:38 -0800823 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700824 throw new IllegalStateException("KeyStore isn't unlocked");
825 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400826 UserManager mgr = UserManager.get(mContext);
827 UserInfo user = mgr.getUserInfo(mUserId);
828 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
829 throw new SecurityException("Restricted users cannot establish VPNs");
830 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700831
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900832 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
833 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
834 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700835
836 // Load certificates.
837 String privateKey = "";
838 String userCert = "";
839 String caCert = "";
840 String serverCert = "";
841 if (!profile.ipsecUserCert.isEmpty()) {
842 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
843 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700844 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700845 }
846 if (!profile.ipsecCaCert.isEmpty()) {
847 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700848 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700849 }
850 if (!profile.ipsecServerCert.isEmpty()) {
851 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700852 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700853 }
854 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
855 throw new IllegalStateException("Cannot load credentials");
856 }
857
858 // Prepare arguments for racoon.
859 String[] racoon = null;
860 switch (profile.type) {
861 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
862 racoon = new String[] {
863 iface, profile.server, "udppsk", profile.ipsecIdentifier,
864 profile.ipsecSecret, "1701",
865 };
866 break;
867 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
868 racoon = new String[] {
869 iface, profile.server, "udprsa", privateKey, userCert,
870 caCert, serverCert, "1701",
871 };
872 break;
873 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
874 racoon = new String[] {
875 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
876 profile.ipsecSecret, profile.username, profile.password, "", gateway,
877 };
878 break;
879 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
880 racoon = new String[] {
881 iface, profile.server, "xauthrsa", privateKey, userCert,
882 caCert, serverCert, profile.username, profile.password, "", gateway,
883 };
884 break;
885 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
886 racoon = new String[] {
887 iface, profile.server, "hybridrsa",
888 caCert, serverCert, profile.username, profile.password, "", gateway,
889 };
890 break;
891 }
892
893 // Prepare arguments for mtpd.
894 String[] mtpd = null;
895 switch (profile.type) {
896 case VpnProfile.TYPE_PPTP:
897 mtpd = new String[] {
898 iface, "pptp", profile.server, "1723",
899 "name", profile.username, "password", profile.password,
900 "linkname", "vpn", "refuse-eap", "nodefaultroute",
901 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
902 (profile.mppe ? "+mppe" : "nomppe"),
903 };
904 break;
905 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
906 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
907 mtpd = new String[] {
908 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
909 "name", profile.username, "password", profile.password,
910 "linkname", "vpn", "refuse-eap", "nodefaultroute",
911 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
912 };
913 break;
914 }
915
916 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700917 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700918 config.user = profile.key;
919 config.interfaze = iface;
920 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700921
922 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700923 if (!profile.dnsServers.isEmpty()) {
924 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
925 }
926 if (!profile.searchDomains.isEmpty()) {
927 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
928 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700929 startLegacyVpn(config, racoon, mtpd);
930 }
931
932 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
933 stopLegacyVpn();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700934
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700935 // Prepare for the new request. This also checks the caller.
936 prepare(null, VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700937 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700938
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700939 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700940 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
941 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700942 }
943
Jeff Sharkey899223b2012-08-04 15:24:58 -0700944 public synchronized void stopLegacyVpn() {
945 if (mLegacyVpnRunner != null) {
946 mLegacyVpnRunner.exit();
947 mLegacyVpnRunner = null;
948
949 synchronized (LegacyVpnRunner.TAG) {
950 // wait for old thread to completely finish before spinning up
951 // new instance, otherwise state updates can be out of order.
952 }
953 }
954 }
955
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700956 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700957 * Return the information of the current ongoing legacy VPN.
958 */
959 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700960 // Check if the caller is authorized.
961 enforceControlPermission();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700962 if (mLegacyVpnRunner == null) return null;
963
964 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -0700965 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700966 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
967 if (mNetworkInfo.isConnected()) {
968 info.intent = mStatusIntent;
969 }
970 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700971 }
972
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700973 public VpnConfig getLegacyVpnConfig() {
974 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700975 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700976 } else {
977 return null;
978 }
979 }
980
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700981 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700982 * Bringing up a VPN connection takes time, and that is all this thread
983 * does. Here we have plenty of time. The only thing we need to take
984 * care of is responding to interruptions as soon as possible. Otherwise
985 * requests will be piled up. This can be done in a Handler as a state
986 * machine, but it is much easier to read in the current form.
987 */
988 private class LegacyVpnRunner extends Thread {
989 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700990
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700991 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700992 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700993 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700994 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700995 private final AtomicInteger mOuterConnection =
996 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700997
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700998 private long mTimer = -1;
999
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001000 /**
1001 * Watch for the outer connection (passing in the constructor) going away.
1002 */
1003 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1004 @Override
1005 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001006 if (!mEnableTeardown) return;
1007
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001008 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1009 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1010 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1011 NetworkInfo info = (NetworkInfo)intent.getExtra(
1012 ConnectivityManager.EXTRA_NETWORK_INFO);
1013 if (info != null && !info.isConnectedOrConnecting()) {
1014 try {
1015 mObserver.interfaceStatusChanged(mOuterInterface, false);
1016 } catch (RemoteException e) {}
1017 }
1018 }
1019 }
1020 }
1021 };
1022
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001023 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001024 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001025 mConfig = config;
1026 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001027 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001028 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001029 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001030
1031 // This is the interface which VPN is running on,
1032 // mConfig.interfaze will change to point to OUR
1033 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001034 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001035 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001036 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001037 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001038
1039 try {
1040 mOuterConnection.set(
1041 mConnService.findConnectionTypeForIface(mOuterInterface));
1042 } catch (Exception e) {
1043 mOuterConnection.set(ConnectivityManager.TYPE_NONE);
1044 }
1045
1046 IntentFilter filter = new IntentFilter();
1047 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1048 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001049 }
1050
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001051 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001052 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001053 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1054 exit();
1055 }
1056 }
1057
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001058 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001059 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001060 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001061 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001062 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001063 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001064 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001065 try {
1066 mContext.unregisterReceiver(mBroadcastReceiver);
1067 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001068 }
1069
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001070 @Override
1071 public void run() {
1072 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001073 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001074 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001075 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001076 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001077 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001078 }
1079 }
1080
1081 private void checkpoint(boolean yield) throws InterruptedException {
1082 long now = SystemClock.elapsedRealtime();
1083 if (mTimer == -1) {
1084 mTimer = now;
1085 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001086 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001087 Thread.sleep(yield ? 200 : 1);
1088 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001089 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001090 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001091 }
1092 }
1093
1094 private void execute() {
1095 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001096 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001097 try {
1098 // Initialize the timer.
1099 checkpoint(false);
1100
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001101 // Wait for the daemons to stop.
1102 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001103 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001104 checkpoint(true);
1105 }
1106 }
1107
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001108 // Clear the previous state.
1109 File state = new File("/data/misc/vpn/state");
1110 state.delete();
1111 if (state.exists()) {
1112 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001113 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001114 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001115 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001116
Chia-chi Yehe9107902011-07-02 01:48:50 -07001117 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001118 boolean restart = false;
1119 for (String[] arguments : mArguments) {
1120 restart = restart || (arguments != null);
1121 }
1122 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001123 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001124 return;
1125 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001126 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001127
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001128 // Start the daemon with arguments.
1129 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001130 String[] arguments = mArguments[i];
1131 if (arguments == null) {
1132 continue;
1133 }
1134
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001135 // Start the daemon.
1136 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001137 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001138
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001139 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001140 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001141 checkpoint(true);
1142 }
1143
1144 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001145 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001146 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001147 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001148
1149 // Wait for the socket to connect.
1150 while (true) {
1151 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001152 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001153 break;
1154 } catch (Exception e) {
1155 // ignore
1156 }
1157 checkpoint(true);
1158 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001159 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001160
1161 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001162 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001163 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001164 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001165 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001166 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001167 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001168 out.write(bytes.length >> 8);
1169 out.write(bytes.length);
1170 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001171 checkpoint(false);
1172 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001173 out.write(0xFF);
1174 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001175 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001176
1177 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001178 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001179 while (true) {
1180 try {
1181 if (in.read() == -1) {
1182 break;
1183 }
1184 } catch (Exception e) {
1185 // ignore
1186 }
1187 checkpoint(true);
1188 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001189 }
1190
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001191 // Wait for the daemons to create the new state.
1192 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001193 // Check if a running daemon is dead.
1194 for (int i = 0; i < mDaemons.length; ++i) {
1195 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001196 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001197 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001198 }
1199 }
1200 checkpoint(true);
1201 }
1202
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001203 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001204 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001205 if (parameters.length != 6) {
1206 throw new IllegalStateException("Cannot parse the state");
1207 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001208
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001209 // Set the interface and the addresses in the config.
1210 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001211
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001212 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001213 // Set the routes if they are not set in the config.
1214 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001215 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001216 }
1217
1218 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001219 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001220 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001221 if (!dnsServers.isEmpty()) {
1222 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1223 }
1224 }
1225
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001226 // Set the search domains if they are not set in the config.
1227 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1228 String searchDomains = parameters[4].trim();
1229 if (!searchDomains.isEmpty()) {
1230 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1231 }
1232 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001233
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001234 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001235 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001236 // Set the start time
1237 mConfig.startTime = SystemClock.elapsedRealtime();
1238
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001239 // Check if the thread is interrupted while we are waiting.
1240 checkpoint(false);
1241
Chia-chi Yehe9107902011-07-02 01:48:50 -07001242 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001243 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001244 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001245 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001246
1247 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001248 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001249 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001250 mAllowIPv4 = mConfig.allowIPv4;
1251 mAllowIPv6 = mConfig.allowIPv6;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001252
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001253 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001254
1255 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001256 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001257 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001258 Log.i(TAG, "Aborting", e);
Chia-chi Yehe9107902011-07-02 01:48:50 -07001259 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001260 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001261 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001262 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001263 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001264 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001265 }
1266 }
1267
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001268 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001269 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001270 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001271 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001272 }
1273 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001274
1275 /**
1276 * Monitor the daemons we started, moving to disconnected state if the
1277 * underlying services fail.
1278 */
1279 private void monitorDaemons() {
1280 if (!mNetworkInfo.isConnected()) {
1281 return;
1282 }
1283
1284 try {
1285 while (true) {
1286 Thread.sleep(2000);
1287 for (int i = 0; i < mDaemons.length; i++) {
1288 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1289 return;
1290 }
1291 }
1292 }
1293 } catch (InterruptedException e) {
1294 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1295 } finally {
1296 for (String daemon : mDaemons) {
1297 SystemService.stop(daemon);
1298 }
1299
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001300 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001301 }
1302 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001303 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001304}