blob: 3a2391f1abca1306225ff7632855c7742948cdea [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;
20
Chad Brubaker4ca19e82013-06-14 11:16:51 -070021import android.app.AppGlobals;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070022import android.app.Notification;
23import android.app.NotificationManager;
Jeff Sharkey899223b2012-08-04 15:24:58 -070024import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070025import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070026import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070027import android.content.Context;
28import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070029import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070030import android.content.ServiceConnection;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070031import android.content.pm.ApplicationInfo;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070032import android.content.pm.IPackageManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070033import android.content.pm.PackageManager;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070034import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070035import android.content.pm.UserInfo;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070036import android.graphics.Bitmap;
37import android.graphics.Canvas;
38import android.graphics.drawable.Drawable;
Jeff Sharkey899223b2012-08-04 15:24:58 -070039import android.net.BaseNetworkStateTracker;
40import android.net.ConnectivityManager;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070041import android.net.IConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070042import android.net.INetworkManagementEventObserver;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070043import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070044import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070045import android.net.LocalSocket;
46import android.net.LocalSocketAddress;
Jeff Sharkey899223b2012-08-04 15:24:58 -070047import android.net.NetworkInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -070048import android.net.RouteInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070049import android.net.NetworkInfo.DetailedState;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070050import android.os.Binder;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080051import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070052import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070053import android.os.INetworkManagementService;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070054import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070055import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070056import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070057import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070058import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070059import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070060import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070061import android.os.UserManager;
Jeff Sharkey82f85212012-08-24 11:17:25 -070062import android.security.Credentials;
63import android.security.KeyStore;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070064import android.util.Log;
Chad Brubakerc2865192013-07-10 14:46:23 -070065import android.util.SparseBooleanArray;
Jeff Sharkey82f85212012-08-24 11:17:25 -070066import android.widget.Toast;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070067
Chad Brubakerc2865192013-07-10 14:46:23 -070068import com.android.internal.annotations.GuardedBy;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070069import com.android.internal.R;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070070import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070071import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -070072import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070073import com.android.internal.util.Preconditions;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070074import com.android.server.ConnectivityService.VpnCallback;
Jeff Sharkey899223b2012-08-04 15:24:58 -070075import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070076
Chia-chi Yeh97a61562011-07-14 15:05:05 -070077import java.io.File;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070078import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070079import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070080import java.net.Inet4Address;
81import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070082import java.nio.charset.StandardCharsets;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070083import java.util.Arrays;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070084import java.util.List;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070085import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070086
Jeff Sharkey065b2992012-08-05 14:16:48 -070087import libcore.io.IoUtils;
88
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070089/**
90 * @hide
91 */
Jeff Sharkey899223b2012-08-04 15:24:58 -070092public class Vpn extends BaseNetworkStateTracker {
93 private static final String TAG = "Vpn";
94 private static final boolean LOGD = true;
95
96 // TODO: create separate trackers for each unique VPN to support
97 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070098
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070099 private final VpnCallback mCallback;
100
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700101 private String mPackage = VpnConfig.LEGACY_VPN;
102 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700103 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700104 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700105 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700106 private volatile boolean mEnableNotif = true;
107 private volatile boolean mEnableTeardown = true;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700108 private final IConnectivityManager mConnService;
Chad Brubakerc2865192013-07-10 14:46:23 -0700109 private VpnConfig mConfig;
110
111 /* list of users using this VPN. */
112 @GuardedBy("this")
113 private SparseBooleanArray mVpnUsers = null;
114 private BroadcastReceiver mUserIntentReceiver = null;
115
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700116 private final int mUserId;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700117
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700118 public Vpn(Context context, VpnCallback callback, INetworkManagementService netService,
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700119 IConnectivityManager connService, int userId) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700120 // TODO: create dedicated TYPE_VPN network type
121 super(ConnectivityManager.TYPE_DUMMY);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700122 mContext = context;
123 mCallback = callback;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700124 mConnService = connService;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700125 mUserId = userId;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700126
127 try {
128 netService.registerObserver(mObserver);
129 } catch (RemoteException e) {
130 Log.wtf(TAG, "Problem registering observer", e);
131 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700132 if (userId == UserHandle.USER_OWNER) {
133 // Owner's VPN also needs to handle restricted users
134 mUserIntentReceiver = new BroadcastReceiver() {
135 @Override
136 public void onReceive(Context context, Intent intent) {
137 final String action = intent.getAction();
138 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
139 UserHandle.USER_NULL);
140 if (userId == UserHandle.USER_NULL) return;
141
142 if (Intent.ACTION_USER_ADDED.equals(action)) {
143 onUserAdded(userId);
144 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
145 onUserRemoved(userId);
146 }
147 }
148 };
149
150 IntentFilter intentFilter = new IntentFilter();
151 intentFilter.addAction(Intent.ACTION_USER_ADDED);
152 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
153 mContext.registerReceiverAsUser(
154 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
155 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700156 }
157
Jeff Sharkey57666932013-04-30 17:01:57 -0700158 /**
159 * Set if this object is responsible for showing its own notifications. When
160 * {@code false}, notifications are handled externally by someone else.
161 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700162 public void setEnableNotifications(boolean enableNotif) {
163 mEnableNotif = enableNotif;
164 }
165
Jeff Sharkey57666932013-04-30 17:01:57 -0700166 /**
167 * Set if this object is responsible for watching for {@link NetworkInfo}
168 * teardown. When {@code false}, teardown is handled externally by someone
169 * else.
170 */
171 public void setEnableTeardown(boolean enableTeardown) {
172 mEnableTeardown = enableTeardown;
173 }
174
Jeff Sharkey899223b2012-08-04 15:24:58 -0700175 @Override
176 protected void startMonitoringInternal() {
177 // Ignored; events are sent through callbacks for now
178 }
179
180 @Override
181 public boolean teardown() {
182 // TODO: finish migration to unique tracker for each VPN
183 throw new UnsupportedOperationException();
184 }
185
186 @Override
187 public boolean reconnect() {
188 // TODO: finish migration to unique tracker for each VPN
189 throw new UnsupportedOperationException();
190 }
191
192 @Override
193 public String getTcpBufferSizesPropName() {
194 return PROP_TCP_BUFFER_UNKNOWN;
195 }
196
197 /**
198 * Update current state, dispaching event to listeners.
199 */
200 private void updateState(DetailedState detailedState, String reason) {
201 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
202 mNetworkInfo.setDetailedState(detailedState, reason, null);
203 mCallback.onStateChanged(new NetworkInfo(mNetworkInfo));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700204 }
205
206 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700207 * Prepare for a VPN application. This method is designed to solve
208 * race conditions. It first compares the current prepared package
209 * with {@code oldPackage}. If they are the same, the prepared
210 * package is revoked and replaced with {@code newPackage}. If
211 * {@code oldPackage} is {@code null}, the comparison is omitted.
212 * If {@code newPackage} is the same package or {@code null}, the
213 * revocation is omitted. This method returns {@code true} if the
214 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700215 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700216 * Legacy VPN is handled specially since it is not a real package.
217 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
218 * it can be revoked by itself.
219 *
220 * @param oldPackage The package name of the old VPN application.
221 * @param newPackage The package name of the new VPN application.
222 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700223 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700224 public synchronized boolean prepare(String oldPackage, String newPackage) {
225 // Return false if the package does not match.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700226 if (oldPackage != null && !oldPackage.equals(mPackage)) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700227 return false;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700228 }
229
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700230 // Return true if we do not need to revoke.
231 if (newPackage == null ||
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700232 (newPackage.equals(mPackage) && !newPackage.equals(VpnConfig.LEGACY_VPN))) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700233 return true;
234 }
235
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700236 // Check if the caller is authorized.
237 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700238
Chia-chi Yehe9107902011-07-02 01:48:50 -0700239 // Reset the interface and hide the notification.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700240 if (mInterface != null) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700241 final long token = Binder.clearCallingIdentity();
242 try {
243 mCallback.restore();
Chad Brubakerc2865192013-07-10 14:46:23 -0700244 final int size = mVpnUsers.size();
245 for (int i = 0; i < size; i++) {
246 int user = mVpnUsers.keyAt(i);
247 mCallback.clearUserForwarding(mInterface, user);
248 hideNotification(user);
249 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700250
251 mCallback.clearMarkedForwarding(mInterface);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700252 } finally {
253 Binder.restoreCallingIdentity(token);
254 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700255 jniReset(mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700256 mInterface = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700257 mVpnUsers = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700258 }
259
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700260 // Revoke the connection or stop LegacyVpnRunner.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700261 if (mConnection != null) {
262 try {
263 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
264 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
265 } catch (Exception e) {
266 // ignore
267 }
268 mContext.unbindService(mConnection);
269 mConnection = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700270 } else if (mLegacyVpnRunner != null) {
271 mLegacyVpnRunner.exit();
272 mLegacyVpnRunner = null;
273 }
274
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700275 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
276 mPackage = newPackage;
Chad Brubakerc2865192013-07-10 14:46:23 -0700277 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700278 updateState(DetailedState.IDLE, "prepare");
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700279 return true;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700280 }
281
282 /**
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700283 * Protect a socket from routing changes by binding it to the given
284 * interface. The socket is NOT closed by this method.
285 *
286 * @param socket The socket to be bound.
Jeff Sharkey899223b2012-08-04 15:24:58 -0700287 * @param interfaze The name of the interface.
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700288 */
289 public void protect(ParcelFileDescriptor socket, String interfaze) throws Exception {
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700290
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700291 PackageManager pm = mContext.getPackageManager();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700292 int appUid = pm.getPackageUid(mPackage, mUserId);
293 if (Binder.getCallingUid() != appUid) {
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700294 throw new SecurityException("Unauthorized Caller");
295 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700296 // protect the socket from routing rules
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700297 final long token = Binder.clearCallingIdentity();
298 try {
299 mCallback.protect(socket);
300 } finally {
301 Binder.restoreCallingIdentity(token);
302 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700303 // bind the socket to the interface
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700304 jniProtect(socket.getFd(), interfaze);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700305
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700306 }
307
308 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700309 * Establish a VPN network and return the file descriptor of the VPN
310 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700311 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700312 *
313 * @param config The parameters to configure the network.
314 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700315 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700316 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700317 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700318 UserManager mgr = UserManager.get(mContext);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700319 PackageManager pm = mContext.getPackageManager();
320 ApplicationInfo app = null;
321 try {
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700322 app = AppGlobals.getPackageManager().getApplicationInfo(mPackage, 0, mUserId);
323 if (Binder.getCallingUid() != app.uid) {
324 return null;
325 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700326 } catch (Exception e) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700327 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700328 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700329 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700330 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
331 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700332 long token = Binder.clearCallingIdentity();
333 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700334 // Restricted users are not allowed to create VPNs, they are tied to Owner
335 UserInfo user = mgr.getUserInfo(mUserId);
336 if (user.isRestricted()) {
337 throw new SecurityException("Restricted users cannot establish VPNs");
338 }
339
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700340 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
341 null, 0, mUserId);
342 if (info == null) {
343 throw new SecurityException("Cannot find " + config.user);
344 }
345 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
346 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
347 }
348 } catch (RemoteException e) {
349 throw new SecurityException("Cannot find " + config.user);
350 } finally {
351 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700352 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700353
Chia-chi Yehe9107902011-07-02 01:48:50 -0700354 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700355 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700356 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700357 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700358 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700359
Chad Brubakerc2865192013-07-10 14:46:23 -0700360 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700361 StringBuilder builder = new StringBuilder();
362 for (LinkAddress address : config.addresses) {
363 builder.append(" " + address);
364 }
365 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700366 throw new IllegalArgumentException("At least one address must be specified");
367 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700368 Connection connection = new Connection();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700369 if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
370 new UserHandle(mUserId))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700371 throw new IllegalStateException("Cannot bind " + config.user);
372 }
373 if (mConnection != null) {
374 mContext.unbindService(mConnection);
375 }
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700376 if (mInterface != null && !mInterface.equals(interfaze)) {
377 jniReset(mInterface);
Chia-chi Yehf4e3bf82011-06-30 12:33:17 -0700378 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700379 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700380 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700381
382 // Fill more values.
383 config.user = mPackage;
384 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700385 config.startTime = SystemClock.elapsedRealtime();
386 mConfig = config;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700387 // Set up forwarding and DNS rules.
Chad Brubakerc2865192013-07-10 14:46:23 -0700388 mVpnUsers = new SparseBooleanArray();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700389 token = Binder.clearCallingIdentity();
390 try {
391 mCallback.setMarkedForwarding(mInterface);
392 mCallback.setRoutes(interfaze, config.routes);
393 mCallback.override(mInterface, config.dnsServers, config.searchDomains);
Chad Brubakerc2865192013-07-10 14:46:23 -0700394 addVpnUserLocked(mUserId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700395
396 } finally {
397 Binder.restoreCallingIdentity(token);
398 }
399
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700400 } catch (RuntimeException e) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700401 updateState(DetailedState.FAILED, "establish");
Jeff Sharkey065b2992012-08-05 14:16:48 -0700402 IoUtils.closeQuietly(tun);
Chad Brubakerc2865192013-07-10 14:46:23 -0700403 // make sure marked forwarding is cleared if it was set
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700404 try {
405 mCallback.clearMarkedForwarding(mInterface);
406 } catch (Exception ingored) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700407 // ignored
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700408 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700409 throw e;
410 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700411 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700412
Chia-chi Yeh8909b102011-07-01 01:09:42 -0700413
Chad Brubakerc2865192013-07-10 14:46:23 -0700414 // If we are owner assign all Restricted Users to this VPN
415 if (mUserId == UserHandle.USER_OWNER) {
416 token = Binder.clearCallingIdentity();
417 try {
418 for (UserInfo user : mgr.getUsers()) {
419 if (user.isRestricted()) {
420 try {
421 addVpnUserLocked(user.id);
422 } catch (Exception e) {
423 Log.wtf(TAG, "Failed to add user " + user.id + " to owner's VPN");
424 }
425 }
426 }
427 } finally {
428 Binder.restoreCallingIdentity(token);
429 }
430 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700431 // TODO: ensure that contract class eventually marks as connected
432 updateState(DetailedState.AUTHENTICATING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700433 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700434 }
435
Chad Brubakerc2865192013-07-10 14:46:23 -0700436 private boolean isRunningLocked() {
437 return mVpnUsers != null;
438 }
439
440 private void addVpnUserLocked(int user) {
441 enforceControlPermission();
442
443 if (!isRunningLocked()) {
444 throw new IllegalStateException("VPN is not active");
445 }
446 // add the user
447 mCallback.addUserForwarding(mInterface, user);
448 mVpnUsers.put(user, true);
449
450 // show the notification
451 if (!mPackage.equals(VpnConfig.LEGACY_VPN)) {
452 // Load everything for the user's notification
453 PackageManager pm = mContext.getPackageManager();
454 ApplicationInfo app = null;
455 try {
456 app = AppGlobals.getPackageManager().getApplicationInfo(mPackage, 0, mUserId);
457 } catch (RemoteException e) {
458 throw new IllegalStateException("Invalid application");
459 }
460 String label = app.loadLabel(pm).toString();
461 // Load the icon and convert it into a bitmap.
462 Drawable icon = app.loadIcon(pm);
463 Bitmap bitmap = null;
464 if (icon.getIntrinsicWidth() > 0 && icon.getIntrinsicHeight() > 0) {
465 int width = mContext.getResources().getDimensionPixelSize(
466 android.R.dimen.notification_large_icon_width);
467 int height = mContext.getResources().getDimensionPixelSize(
468 android.R.dimen.notification_large_icon_height);
469 icon.setBounds(0, 0, width, height);
470 bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
471 Canvas c = new Canvas(bitmap);
472 icon.draw(c);
473 c.setBitmap(null);
474 }
475 showNotification(label, bitmap, user);
476 } else {
477 showNotification(null, null, user);
478 }
479 }
480
481 private void removeVpnUserLocked(int user) {
482 enforceControlPermission();
483
484 if (!isRunningLocked()) {
485 throw new IllegalStateException("VPN is not active");
486 }
487 mCallback.clearUserForwarding(mInterface, user);
488 mVpnUsers.delete(user);
489 hideNotification(user);
490 }
491
492 private void onUserAdded(int userId) {
493 // If the user is restricted tie them to the owner's VPN
494 synchronized(Vpn.this) {
495 UserManager mgr = UserManager.get(mContext);
496 UserInfo user = mgr.getUserInfo(userId);
497 if (user.isRestricted()) {
498 try {
499 addVpnUserLocked(userId);
500 } catch (Exception e) {
501 Log.wtf(TAG, "Failed to add restricted user to owner", e);
502 }
503 }
504 }
505 }
506
507 private void onUserRemoved(int userId) {
508 // clean up if restricted
509 synchronized(Vpn.this) {
510 UserManager mgr = UserManager.get(mContext);
511 UserInfo user = mgr.getUserInfo(userId);
512 if (user.isRestricted()) {
513 try {
514 removeVpnUserLocked(userId);
515 } catch (Exception e) {
516 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
517 }
518 }
519 }
520 }
521
Jeff Sharkey899223b2012-08-04 15:24:58 -0700522 @Deprecated
523 public synchronized void interfaceStatusChanged(String iface, boolean up) {
524 try {
525 mObserver.interfaceStatusChanged(iface, up);
526 } catch (RemoteException e) {
527 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700528 }
529 }
530
Jeff Sharkey899223b2012-08-04 15:24:58 -0700531 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
532 @Override
533 public void interfaceStatusChanged(String interfaze, boolean up) {
534 synchronized (Vpn.this) {
535 if (!up && mLegacyVpnRunner != null) {
536 mLegacyVpnRunner.check(interfaze);
537 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700538 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700539 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700540
Jeff Sharkey899223b2012-08-04 15:24:58 -0700541 @Override
542 public void interfaceRemoved(String interfaze) {
543 synchronized (Vpn.this) {
544 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
545 final long token = Binder.clearCallingIdentity();
546 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700547 final int size = mVpnUsers.size();
548 for (int i = 0; i < size; i++) {
549 int user = mVpnUsers.keyAt(i);
550 mCallback.clearUserForwarding(mInterface, user);
551 hideNotification(user);
552 }
553 mVpnUsers = null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700554 mCallback.clearMarkedForwarding(mInterface);
555
Jeff Sharkey899223b2012-08-04 15:24:58 -0700556 mCallback.restore();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700557 } finally {
558 Binder.restoreCallingIdentity(token);
559 }
560 mInterface = null;
561 if (mConnection != null) {
562 mContext.unbindService(mConnection);
563 mConnection = null;
564 updateState(DetailedState.DISCONNECTED, "interfaceRemoved");
565 } else if (mLegacyVpnRunner != null) {
566 mLegacyVpnRunner.exit();
567 mLegacyVpnRunner = null;
568 }
569 }
570 }
571 }
572 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700573
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700574 private void enforceControlPermission() {
575 // System user is allowed to control VPN.
576 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
577 return;
578 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700579 int appId = UserHandle.getAppId(Binder.getCallingUid());
580 final long token = Binder.clearCallingIdentity();
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700581 try {
582 // System dialogs are also allowed to control VPN.
583 PackageManager pm = mContext.getPackageManager();
584 ApplicationInfo app = pm.getApplicationInfo(VpnConfig.DIALOGS_PACKAGE, 0);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700585 if (appId == app.uid) {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700586 return;
587 }
588 } catch (Exception e) {
589 // ignore
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700590 } finally {
591 Binder.restoreCallingIdentity(token);
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700592 }
593
594 throw new SecurityException("Unauthorized Caller");
595 }
596
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700597 private class Connection implements ServiceConnection {
598 private IBinder mService;
599
600 @Override
601 public void onServiceConnected(ComponentName name, IBinder service) {
602 mService = service;
603 }
604
605 @Override
606 public void onServiceDisconnected(ComponentName name) {
607 mService = null;
608 }
609 }
610
Chad Brubakerc2865192013-07-10 14:46:23 -0700611 private void showNotification(String label, Bitmap icon, int user) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700612 if (!mEnableNotif) return;
Chad Brubakerc2865192013-07-10 14:46:23 -0700613 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext, mConfig);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700614
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700615 NotificationManager nm = (NotificationManager)
616 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
617
618 if (nm != null) {
Chia-chi Yeha4b87b52011-06-30 23:21:55 -0700619 String title = (label == null) ? mContext.getString(R.string.vpn_title) :
620 mContext.getString(R.string.vpn_title_long, label);
Chad Brubakerc2865192013-07-10 14:46:23 -0700621 String text = (mConfig.session == null) ? mContext.getString(R.string.vpn_text) :
622 mContext.getString(R.string.vpn_text_long, mConfig.session);
Chia-chi Yeha4b87b52011-06-30 23:21:55 -0700623
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700624 Notification notification = new Notification.Builder(mContext)
625 .setSmallIcon(R.drawable.vpn_connected)
Chia-chi Yeha4b87b52011-06-30 23:21:55 -0700626 .setLargeIcon(icon)
627 .setContentTitle(title)
Chia-chi Yehf8905fd2011-06-14 16:35:02 -0700628 .setContentText(text)
Jeff Sharkey899223b2012-08-04 15:24:58 -0700629 .setContentIntent(mStatusIntent)
Chia-chi Yeh50fe7092012-01-11 14:26:24 -0800630 .setDefaults(0)
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700631 .setOngoing(true)
Jeff Sharkey899223b2012-08-04 15:24:58 -0700632 .build();
Chad Brubakerc2865192013-07-10 14:46:23 -0700633 nm.notifyAsUser(null, R.drawable.vpn_connected, notification, new UserHandle(user));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700634 }
635 }
636
Chad Brubakerc2865192013-07-10 14:46:23 -0700637 private void hideNotification(int user) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700638 if (!mEnableNotif) return;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700639 mStatusIntent = null;
640
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700641 NotificationManager nm = (NotificationManager)
642 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
643
644 if (nm != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700645 nm.cancelAsUser(null, R.drawable.vpn_connected, new UserHandle(user));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700646 }
647 }
648
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700649 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700650 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700651 private native int jniSetAddresses(String interfaze, String addresses);
652 private native int jniSetRoutes(String interfaze, String routes);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700653 private native void jniReset(String interfaze);
654 private native int jniCheck(String interfaze);
655 private native void jniProtect(int socket, String interfaze);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700656
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900657 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
658 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700659 // Currently legacy VPN only works on IPv4.
660 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900661 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700662 }
663 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700664
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900665 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700666 }
667
668 /**
669 * Start legacy VPN, controlling native daemons as needed. Creates a
670 * secondary thread to perform connection work, returning quickly.
671 */
672 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800673 enforceControlPermission();
Kenny Rootb9594ce2013-02-14 10:18:38 -0800674 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700675 throw new IllegalStateException("KeyStore isn't unlocked");
676 }
677
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900678 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
679 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
680 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700681
682 // Load certificates.
683 String privateKey = "";
684 String userCert = "";
685 String caCert = "";
686 String serverCert = "";
687 if (!profile.ipsecUserCert.isEmpty()) {
688 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
689 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700690 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700691 }
692 if (!profile.ipsecCaCert.isEmpty()) {
693 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700694 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700695 }
696 if (!profile.ipsecServerCert.isEmpty()) {
697 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700698 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700699 }
700 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
701 throw new IllegalStateException("Cannot load credentials");
702 }
703
704 // Prepare arguments for racoon.
705 String[] racoon = null;
706 switch (profile.type) {
707 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
708 racoon = new String[] {
709 iface, profile.server, "udppsk", profile.ipsecIdentifier,
710 profile.ipsecSecret, "1701",
711 };
712 break;
713 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
714 racoon = new String[] {
715 iface, profile.server, "udprsa", privateKey, userCert,
716 caCert, serverCert, "1701",
717 };
718 break;
719 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
720 racoon = new String[] {
721 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
722 profile.ipsecSecret, profile.username, profile.password, "", gateway,
723 };
724 break;
725 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
726 racoon = new String[] {
727 iface, profile.server, "xauthrsa", privateKey, userCert,
728 caCert, serverCert, profile.username, profile.password, "", gateway,
729 };
730 break;
731 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
732 racoon = new String[] {
733 iface, profile.server, "hybridrsa",
734 caCert, serverCert, profile.username, profile.password, "", gateway,
735 };
736 break;
737 }
738
739 // Prepare arguments for mtpd.
740 String[] mtpd = null;
741 switch (profile.type) {
742 case VpnProfile.TYPE_PPTP:
743 mtpd = new String[] {
744 iface, "pptp", profile.server, "1723",
745 "name", profile.username, "password", profile.password,
746 "linkname", "vpn", "refuse-eap", "nodefaultroute",
747 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
748 (profile.mppe ? "+mppe" : "nomppe"),
749 };
750 break;
751 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
752 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
753 mtpd = new String[] {
754 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
755 "name", profile.username, "password", profile.password,
756 "linkname", "vpn", "refuse-eap", "nodefaultroute",
757 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
758 };
759 break;
760 }
761
762 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700763 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700764 config.user = profile.key;
765 config.interfaze = iface;
766 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700767
768 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700769 if (!profile.dnsServers.isEmpty()) {
770 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
771 }
772 if (!profile.searchDomains.isEmpty()) {
773 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
774 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700775 startLegacyVpn(config, racoon, mtpd);
776 }
777
778 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
779 stopLegacyVpn();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700780
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700781 // Prepare for the new request. This also checks the caller.
782 prepare(null, VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700783 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700784
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700785 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700786 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
787 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700788 }
789
Jeff Sharkey899223b2012-08-04 15:24:58 -0700790 public synchronized void stopLegacyVpn() {
791 if (mLegacyVpnRunner != null) {
792 mLegacyVpnRunner.exit();
793 mLegacyVpnRunner = null;
794
795 synchronized (LegacyVpnRunner.TAG) {
796 // wait for old thread to completely finish before spinning up
797 // new instance, otherwise state updates can be out of order.
798 }
799 }
800 }
801
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700802 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700803 * Return the information of the current ongoing legacy VPN.
804 */
805 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700806 // Check if the caller is authorized.
807 enforceControlPermission();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700808 if (mLegacyVpnRunner == null) return null;
809
810 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -0700811 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700812 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
813 if (mNetworkInfo.isConnected()) {
814 info.intent = mStatusIntent;
815 }
816 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700817 }
818
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700819 public VpnConfig getLegacyVpnConfig() {
820 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700821 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700822 } else {
823 return null;
824 }
825 }
826
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700827 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700828 * Bringing up a VPN connection takes time, and that is all this thread
829 * does. Here we have plenty of time. The only thing we need to take
830 * care of is responding to interruptions as soon as possible. Otherwise
831 * requests will be piled up. This can be done in a Handler as a state
832 * machine, but it is much easier to read in the current form.
833 */
834 private class LegacyVpnRunner extends Thread {
835 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700836
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700837 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700838 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700839 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700840 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700841 private final AtomicInteger mOuterConnection =
842 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700843
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700844 private long mTimer = -1;
845
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700846 /**
847 * Watch for the outer connection (passing in the constructor) going away.
848 */
849 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
850 @Override
851 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -0700852 if (!mEnableTeardown) return;
853
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700854 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
855 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
856 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
857 NetworkInfo info = (NetworkInfo)intent.getExtra(
858 ConnectivityManager.EXTRA_NETWORK_INFO);
859 if (info != null && !info.isConnectedOrConnecting()) {
860 try {
861 mObserver.interfaceStatusChanged(mOuterInterface, false);
862 } catch (RemoteException e) {}
863 }
864 }
865 }
866 }
867 };
868
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700869 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700870 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700871 mConfig = config;
872 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -0700873 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700874 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700875 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700876
877 // This is the interface which VPN is running on,
878 // mConfig.interfaze will change to point to OUR
879 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700880 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700881 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700882 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700883 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700884
885 try {
886 mOuterConnection.set(
887 mConnService.findConnectionTypeForIface(mOuterInterface));
888 } catch (Exception e) {
889 mOuterConnection.set(ConnectivityManager.TYPE_NONE);
890 }
891
892 IntentFilter filter = new IntentFilter();
893 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
894 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700895 }
896
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700897 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700898 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700899 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
900 exit();
901 }
902 }
903
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700904 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700905 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700906 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700907 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -0700908 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700909 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700910 updateState(DetailedState.DISCONNECTED, "exit");
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700911 try {
912 mContext.unregisterReceiver(mBroadcastReceiver);
913 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700914 }
915
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700916 @Override
917 public void run() {
918 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700919 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700920 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700921 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700922 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700923 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700924 }
925 }
926
927 private void checkpoint(boolean yield) throws InterruptedException {
928 long now = SystemClock.elapsedRealtime();
929 if (mTimer == -1) {
930 mTimer = now;
931 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -0700932 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700933 Thread.sleep(yield ? 200 : 1);
934 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700935 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700936 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700937 }
938 }
939
940 private void execute() {
941 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -0700942 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700943 try {
944 // Initialize the timer.
945 checkpoint(false);
946
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700947 // Wait for the daemons to stop.
948 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -0700949 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700950 checkpoint(true);
951 }
952 }
953
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700954 // Clear the previous state.
955 File state = new File("/data/misc/vpn/state");
956 state.delete();
957 if (state.exists()) {
958 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700959 }
Chia-chi Yehc1872732011-12-08 16:51:41 -0800960 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700961 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700962
Chia-chi Yehe9107902011-07-02 01:48:50 -0700963 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700964 boolean restart = false;
965 for (String[] arguments : mArguments) {
966 restart = restart || (arguments != null);
967 }
968 if (!restart) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700969 updateState(DetailedState.DISCONNECTED, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700970 return;
971 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700972 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700973
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700974 // Start the daemon with arguments.
975 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700976 String[] arguments = mArguments[i];
977 if (arguments == null) {
978 continue;
979 }
980
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700981 // Start the daemon.
982 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -0700983 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700984
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700985 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -0700986 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700987 checkpoint(true);
988 }
989
990 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700991 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700992 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700993 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700994
995 // Wait for the socket to connect.
996 while (true) {
997 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700998 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700999 break;
1000 } catch (Exception e) {
1001 // ignore
1002 }
1003 checkpoint(true);
1004 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001005 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001006
1007 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001008 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001009 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001010 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001011 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001012 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001013 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001014 out.write(bytes.length >> 8);
1015 out.write(bytes.length);
1016 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001017 checkpoint(false);
1018 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001019 out.write(0xFF);
1020 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001021 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001022
1023 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001024 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001025 while (true) {
1026 try {
1027 if (in.read() == -1) {
1028 break;
1029 }
1030 } catch (Exception e) {
1031 // ignore
1032 }
1033 checkpoint(true);
1034 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001035 }
1036
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001037 // Wait for the daemons to create the new state.
1038 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001039 // Check if a running daemon is dead.
1040 for (int i = 0; i < mDaemons.length; ++i) {
1041 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001042 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001043 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001044 }
1045 }
1046 checkpoint(true);
1047 }
1048
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001049 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001050 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001051 if (parameters.length != 6) {
1052 throw new IllegalStateException("Cannot parse the state");
1053 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001054
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001055 // Set the interface and the addresses in the config.
1056 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001057
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001058 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001059 // Set the routes if they are not set in the config.
1060 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001061 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001062 }
1063
1064 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001065 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001066 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001067 if (!dnsServers.isEmpty()) {
1068 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1069 }
1070 }
1071
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001072 // Set the search domains if they are not set in the config.
1073 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1074 String searchDomains = parameters[4].trim();
1075 if (!searchDomains.isEmpty()) {
1076 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1077 }
1078 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001079
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001080 // Set the routes.
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001081 long token = Binder.clearCallingIdentity();
1082 try {
1083 mCallback.setMarkedForwarding(mConfig.interfaze);
1084 mCallback.setRoutes(mConfig.interfaze, mConfig.routes);
1085 } finally {
1086 Binder.restoreCallingIdentity(token);
1087 }
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001088
1089 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001090 synchronized (Vpn.this) {
1091 // Check if the thread is interrupted while we are waiting.
1092 checkpoint(false);
1093
Chia-chi Yehe9107902011-07-02 01:48:50 -07001094 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001095 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001096 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001097 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001098
1099 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001100 mInterface = mConfig.interfaze;
Chad Brubakerc2865192013-07-10 14:46:23 -07001101 mVpnUsers = new SparseBooleanArray();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001102
1103 token = Binder.clearCallingIdentity();
1104 try {
1105 mCallback.override(mInterface, mConfig.dnsServers, mConfig.searchDomains);
Chad Brubakerc2865192013-07-10 14:46:23 -07001106 addVpnUserLocked(mUserId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001107 } finally {
1108 Binder.restoreCallingIdentity(token);
1109 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001110
Chad Brubakerc2865192013-07-10 14:46:23 -07001111 // Assign all restircted users to this VPN
1112 // (Legacy VPNs are Owner only)
1113 UserManager mgr = UserManager.get(mContext);
1114 token = Binder.clearCallingIdentity();
1115 try {
1116 for (UserInfo user : mgr.getUsers()) {
1117 if (user.isRestricted()) {
1118 try {
1119 addVpnUserLocked(user.id);
1120 } catch (Exception e) {
1121 Log.wtf(TAG, "Failed to add user " + user.id
1122 + " to owner's VPN");
1123 }
1124 }
1125 }
1126 } finally {
1127 Binder.restoreCallingIdentity(token);
1128 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001129 Log.i(TAG, "Connected!");
Jeff Sharkey899223b2012-08-04 15:24:58 -07001130 updateState(DetailedState.CONNECTED, "execute");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001131 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001132 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001133 Log.i(TAG, "Aborting", e);
Chad Brubakerc2865192013-07-10 14:46:23 -07001134 // make sure the routing is cleared
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001135 try {
1136 mCallback.clearMarkedForwarding(mConfig.interfaze);
1137 } catch (Exception ignored) {
1138 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001139 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001140 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001141 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001142 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001143 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001144 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001145 }
1146 }
1147
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001148 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001149 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
1150 updateState(DetailedState.FAILED, "execute");
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001151 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001152 }
1153 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001154
1155 /**
1156 * Monitor the daemons we started, moving to disconnected state if the
1157 * underlying services fail.
1158 */
1159 private void monitorDaemons() {
1160 if (!mNetworkInfo.isConnected()) {
1161 return;
1162 }
1163
1164 try {
1165 while (true) {
1166 Thread.sleep(2000);
1167 for (int i = 0; i < mDaemons.length; i++) {
1168 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1169 return;
1170 }
1171 }
1172 }
1173 } catch (InterruptedException e) {
1174 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1175 } finally {
1176 for (String daemon : mDaemons) {
1177 SystemService.stop(daemon);
1178 }
1179
1180 updateState(DetailedState.DISCONNECTED, "babysit");
1181 }
1182 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001183 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001184}