blob: 1dc2d7e719bb14bd4bac5078bca0d979e579beb3 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 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;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
26import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -070027import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070028import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070029
Wenchao Tongf5ea3402015-03-04 13:26:38 -080030import android.annotation.Nullable;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070031import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070032import android.app.Notification;
33import android.app.NotificationManager;
34import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070035import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.content.ContentResolver;
37import android.content.Context;
38import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070039import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070041import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090042import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070043import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.net.ConnectivityManager;
45import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070046import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070047import android.net.INetworkPolicyListener;
48import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070049import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080050import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070051import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070052import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070053import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070054import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070055import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070057import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070058import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070059import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070060import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070061import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070062import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070063import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040064import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070065import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040066import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040067import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070069import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040070import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070072import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070073import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070074import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Looper;
76import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070077import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070078import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070079import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070080import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070081import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070082import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070084import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040085import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070087import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070088import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070089import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070090import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080091import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070092import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -050093import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070094import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070095import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096
Wink Savilleab9321d2013-06-29 21:10:57 -070097import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -040098import com.android.internal.annotations.GuardedBy;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070099import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700100import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700101import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700102import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800103import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700104import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700105import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700106import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700107import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700108import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700109import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400110import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900111import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700112import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400113import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400114import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700115import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800116import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700117import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700118import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700119import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700120import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700121import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700122
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700123import org.xmlpull.v1.XmlPullParser;
124import org.xmlpull.v1.XmlPullParserException;
125
126import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700128import java.io.FileNotFoundException;
129import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700130import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700132import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700133import java.net.InetAddress;
134import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700135import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700136import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700137import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700138import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700139import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500140import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700141import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700142import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700143import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700144import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
146/**
147 * @hide
148 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800149public class ConnectivityService extends IConnectivityManager.Stub
150 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700151 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700153 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700154 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155
Jake Hamby786e71a2014-02-06 14:43:50 -0800156 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700157
Jeff Sharkey899223b2012-08-04 15:24:58 -0700158 // TODO: create better separation between radio types and network types
159
Robert Greenwalt42acef32009-08-12 16:08:25 -0700160 // how long to wait before switching back to a radio's default network
161 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
162 // system property that can override the above value
163 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
164 "android.telephony.apn-restore";
165
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900166 // How long to wait before putting up a "This network doesn't have an Internet connection,
167 // connect anyway?" dialog after the user selects a network that doesn't validate.
168 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
169
Jeremy Joslin79294842014-12-03 17:15:28 -0800170 // How long to delay to removal of a pending intent based request.
171 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
172 private final int mReleasePendingIntentDelayMs;
173
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800174 private Tethering mTethering;
175
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700176 private final PermissionMonitor mPermissionMonitor;
177
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700178 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700179
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700180 @GuardedBy("mVpns")
181 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700182
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700183 private boolean mLockdownEnabled;
184 private LockdownVpnTracker mLockdownTracker;
185
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700186 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
187 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700188 /** Currently active network rules by UID. */
189 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700190 /** Set of ifaces that are costly. */
191 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700192
Erik Klineda4bfa82015-04-30 12:58:40 +0900193 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700195 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700196 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700198 private Object mDnsLock = new Object();
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800199 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
201 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700202 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700204 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800205 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700206 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700207
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700208 private String mCurrentTcpBufferSizes;
209
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700210 private static final int ENABLED = 1;
211 private static final int DISABLED = 0;
212
Paul Jensenb10e37f2014-11-25 12:33:08 -0500213 // Arguments to rematchNetworkAndRequests()
214 private enum NascentState {
215 // Indicates a network was just validated for the first time. If the network is found to
216 // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down.
217 JUST_VALIDATED,
218 // Indicates a network was not validated for the first time immediately prior to this call.
219 NOT_JUST_VALIDATED
220 };
221 private enum ReapUnvalidatedNetworks {
222 // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming
223 // the highest scoring network satisfying a NetworkRequest. This should be passed when it's
224 // known that there may be unvalidated networks that could potentially be reaped, and when
225 // all networks have been rematched against all NetworkRequests.
226 REAP,
227 // Don't reap unvalidated networks. This should be passed when it's known that there are
228 // no unvalidated networks that could potentially be reaped, and when some networks have
229 // not yet been rematched against all NetworkRequests.
230 DONT_REAP
231 };
232
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700233 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700234 * used internally to change our mobile data enabled flag
235 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700236 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700237
238 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700239 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700240 * from one net to another. Clear happens when we get a new
241 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
242 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700243 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700244 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700245
Robert Greenwalt434203a2010-10-11 16:00:27 -0700246 /**
247 * used internally to reload global proxy settings
248 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700249 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700250
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700251 /**
Wink Saville628b0852011-08-04 15:01:58 -0700252 * used internally to send a sticky broadcast delayed.
253 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700254 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700255
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700256 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400257 * PAC manager has received new port.
258 */
259 private static final int EVENT_PROXY_HAS_CHANGED = 16;
260
Robert Greenwalte049c232014-04-11 15:53:27 -0700261 /**
262 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700263 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700264 */
265 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
266
Robert Greenwalt7b816022014-04-18 15:25:25 -0700267 /**
268 * used internally when registering NetworkAgents
269 * obj = Messenger
270 */
271 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
272
Robert Greenwalt9258c642014-03-26 16:47:06 -0700273 /**
274 * used to add a network request
275 * includes a NetworkRequestInfo
276 */
277 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
278
279 /**
280 * indicates a timeout period is over - check if we had a network yet or not
281 * and if not, call the timeout calback (but leave the request live until they
282 * cancel it.
283 * includes a NetworkRequestInfo
284 */
285 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
286
287 /**
288 * used to add a network listener - no request
289 * includes a NetworkRequestInfo
290 */
291 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
292
293 /**
294 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400295 * arg1 = UID of caller
296 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700297 */
298 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
299
Robert Greenwalta67be032014-05-16 15:49:14 -0700300 /**
301 * used internally when registering NetworkFactories
302 * obj = Messenger
303 */
304 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
305
Robert Greenwalt27711812014-06-25 16:45:57 -0700306 /**
307 * used internally to expire a wakelock when transitioning
308 * from one net to another. Expire happens when we fail to find
309 * a new network (typically after 1 minute) -
310 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
311 * a replacement network.
312 */
313 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
314
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700315 /**
316 * Used internally to indicate the system is ready.
317 */
318 private static final int EVENT_SYSTEM_READY = 25;
319
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800320 /**
321 * used to add a network request with a pending intent
322 * includes a NetworkRequestInfo
323 */
324 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
325
326 /**
327 * used to remove a pending intent and its associated network request.
328 * arg1 = UID of caller
329 * obj = PendingIntent
330 */
331 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
332
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900333 /**
334 * used to specify whether a network should be used even if unvalidated.
335 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
336 * arg2 = whether to remember this choice in the future (1 or 0)
337 * obj = network
338 */
339 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
340
341 /**
342 * used to ask the user to confirm a connection to an unvalidated network.
343 * obj = network
344 */
345 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700346
Erik Klineda4bfa82015-04-30 12:58:40 +0900347 /**
348 * used internally to (re)configure mobile data always-on settings.
349 */
350 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
351
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700352 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700353 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700354 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700355 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700356
Mike Lockwood0f79b542009-08-14 14:18:49 -0400357 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800358 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400359
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700360 private PowerManager.WakeLock mNetTransitionWakeLock;
361 private String mNetTransitionWakeLockCausedBy = "";
362 private int mNetTransitionWakeLockSerialNumber;
363 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800364 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700365
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700366 private InetAddress mDefaultDns;
367
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700368 // used in DBG mode to track inet condition reports
369 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
370 private ArrayList mInetLog;
371
Robert Greenwalt434203a2010-10-11 16:00:27 -0700372 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400373 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700374 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700375 private boolean mDefaultProxyDisabled = false;
376
Robert Greenwalt434203a2010-10-11 16:00:27 -0700377 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400378 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700379
Jason Monk602b2322013-07-03 17:04:33 -0400380 private PacManager mPacManager = null;
381
Erik Klineda4bfa82015-04-30 12:58:40 +0900382 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700383
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400384 private UserManager mUserManager;
385
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700386 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700387 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700388
Robert Greenwalt50393202011-06-21 17:26:14 -0700389 // the set of network types that can only be enabled by system/sig apps
390 List mProtectedNetworks;
391
John Spurlockbf991a82013-06-24 14:20:23 -0400392 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700393
Wink Savilleab9321d2013-06-29 21:10:57 -0700394 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400395
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700396 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
397 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700398 private final static int MAX_NET_ID = 65535;
399 private int mNextNetId = MIN_NET_ID;
400
Robert Greenwalt34524f02014-05-18 16:22:10 -0700401 // sequence number of NetworkRequests
402 private int mNextNetworkRequestId = 1;
403
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700404 /**
405 * Implements support for the legacy "one network per network type" model.
406 *
407 * We used to have a static array of NetworkStateTrackers, one for each
408 * network type, but that doesn't work any more now that we can have,
409 * for example, more that one wifi network. This class stores all the
410 * NetworkAgentInfo objects that support a given type, but the legacy
411 * API will only see the first one.
412 *
413 * It serves two main purposes:
414 *
415 * 1. Provide information about "the network for a given type" (since this
416 * API only supports one).
417 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
418 * the first network for a given type changes, or if the default network
419 * changes.
420 */
421 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900422
423 private static final boolean DBG = true;
424 private static final boolean VDBG = false;
425 private static final String TAG = "CSLegacyTypeTracker";
426
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700427 /**
428 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
429 * Each list holds references to all NetworkAgentInfos that are used to
430 * satisfy requests for that network type.
431 *
432 * This array is built out at startup such that an unsupported network
433 * doesn't get an ArrayList instance, making this a tristate:
434 * unsupported, supported but not active and active.
435 *
436 * The actual lists are populated when we scan the network types that
437 * are supported on this device.
438 */
439 private ArrayList<NetworkAgentInfo> mTypeLists[];
440
441 public LegacyTypeTracker() {
442 mTypeLists = (ArrayList<NetworkAgentInfo>[])
443 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
444 }
445
446 public void addSupportedType(int type) {
447 if (mTypeLists[type] != null) {
448 throw new IllegalStateException(
449 "legacy list for type " + type + "already initialized");
450 }
451 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
452 }
453
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700454 public boolean isTypeSupported(int type) {
455 return isNetworkTypeValid(type) && mTypeLists[type] != null;
456 }
457
458 public NetworkAgentInfo getNetworkForType(int type) {
459 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
460 return mTypeLists[type].get(0);
461 } else {
462 return null;
463 }
464 }
465
Lorenzo Colittia793a672014-07-31 23:20:17 +0900466 private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
467 if (DBG) {
468 log("Sending " + (connected ? "connected" : "disconnected") +
469 " broadcast for type " + type + " " + nai.name() +
470 " isDefaultNetwork=" + isDefaultNetwork(nai));
471 }
472 }
473
474 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700475 public void add(int type, NetworkAgentInfo nai) {
476 if (!isTypeSupported(type)) {
477 return; // Invalid network type.
478 }
479 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
480
481 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
482 if (list.contains(nai)) {
483 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
484 return;
485 }
486
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900487 list.add(nai);
488
489 // Send a broadcast if this is the first network of its type or if it's the default.
490 if (list.size() == 1 || isDefaultNetwork(nai)) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900491 maybeLogBroadcast(nai, true, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700492 sendLegacyNetworkBroadcast(nai, true, type);
493 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700494 }
495
Lorenzo Colittia793a672014-07-31 23:20:17 +0900496 /** Removes the given network from the specified legacy type list. */
497 public void remove(int type, NetworkAgentInfo nai) {
498 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
499 if (list == null || list.isEmpty()) {
500 return;
501 }
502
503 boolean wasFirstNetwork = list.get(0).equals(nai);
504
505 if (!list.remove(nai)) {
506 return;
507 }
508
509 if (wasFirstNetwork || isDefaultNetwork(nai)) {
510 maybeLogBroadcast(nai, false, type);
511 sendLegacyNetworkBroadcast(nai, false, type);
512 }
513
514 if (!list.isEmpty() && wasFirstNetwork) {
515 if (DBG) log("Other network available for type " + type +
516 ", sending connected broadcast");
517 maybeLogBroadcast(list.get(0), false, type);
518 sendLegacyNetworkBroadcast(list.get(0), false, type);
519 }
520 }
521
522 /** Removes the given network from all legacy type lists. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700523 public void remove(NetworkAgentInfo nai) {
524 if (VDBG) log("Removing agent " + nai);
525 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900526 remove(type, nai);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700527 }
528 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700529
Lorenzo Colittia793a672014-07-31 23:20:17 +0900530 private String naiToString(NetworkAgentInfo nai) {
531 String name = (nai != null) ? nai.name() : "null";
532 String state = (nai.networkInfo != null) ?
533 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
534 "???/???";
535 return name + " " + state;
536 }
537
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700538 public void dump(IndentingPrintWriter pw) {
539 for (int type = 0; type < mTypeLists.length; type++) {
540 if (mTypeLists[type] == null) continue;
541 pw.print(type + " ");
542 pw.increaseIndent();
543 if (mTypeLists[type].size() == 0) pw.println("none");
544 for (NetworkAgentInfo nai : mTypeLists[type]) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900545 pw.println(naiToString(nai));
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700546 }
547 pw.decreaseIndent();
548 }
549 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900550
551 // This class needs its own log method because it has a different TAG.
552 private void log(String s) {
553 Slog.d(TAG, s);
554 }
555
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700556 }
557 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
558
Jeff Sharkey899223b2012-08-04 15:24:58 -0700559 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700560 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800561 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800562
Erik Klineda4bfa82015-04-30 12:58:40 +0900563 mDefaultRequest = createInternetRequestForTransport(-1);
564 mNetworkRequests.put(mDefaultRequest, new NetworkRequestInfo(
565 null, mDefaultRequest, new Binder(), NetworkRequestInfo.REQUEST));
566
567 mDefaultMobileDataRequest = createInternetRequestForTransport(
568 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700569
Wink Savillebb08caf2010-09-02 19:23:52 -0700570 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
571 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700572 mHandler = new InternalHandler(handlerThread.getLooper());
573 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700574
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800575 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800576 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
577 String id = Settings.Secure.getString(context.getContentResolver(),
578 Settings.Secure.ANDROID_ID);
579 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700580 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800581 SystemProperties.set("net.hostname", name);
582 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800583 }
584
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700585 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700586 String dns = Settings.Global.getString(context.getContentResolver(),
587 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700588 if (dns == null || dns.length() == 0) {
589 dns = context.getResources().getString(
590 com.android.internal.R.string.config_default_dns_server);
591 }
592 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800593 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
594 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800595 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700596 }
597
Jeremy Joslin79294842014-12-03 17:15:28 -0800598 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
599 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
600
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700601 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700602 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800603 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700604 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700605 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700606 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700607
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700608 try {
609 mPolicyManager.registerListener(mPolicyListener);
610 } catch (RemoteException e) {
611 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700612 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700613 }
614
615 final PowerManager powerManager = (PowerManager) context.getSystemService(
616 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700617 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
618 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
619 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800620 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700621
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700622 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700623
Wink Saville51f456f2013-04-23 14:26:51 -0700624 // TODO: What is the "correct" way to do determine if this is a wifi only device?
625 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
626 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700627 String[] naStrings = context.getResources().getStringArray(
628 com.android.internal.R.array.networkAttributes);
629 for (String naString : naStrings) {
630 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700631 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700632 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700633 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800634 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700635 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700636 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700637 }
Wink Saville51f456f2013-04-23 14:26:51 -0700638 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
639 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
640 n.type);
641 continue;
642 }
Wink Saville975c8482011-04-07 14:23:45 -0700643 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800644 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700645 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700646 continue;
647 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700648 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700649
Wink Saville975c8482011-04-07 14:23:45 -0700650 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700651 mNetworksDefined++;
652 } catch(Exception e) {
653 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700654 }
655 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700656
657 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
658 if (mNetConfigs[TYPE_VPN] == null) {
659 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
660 // don't need to add TYPE_VPN to mNetConfigs.
661 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
662 mNetworksDefined++; // used only in the log() statement below.
663 }
664
Wink Saville5e56bc52013-07-29 15:00:57 -0700665 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700666
Robert Greenwalt50393202011-06-21 17:26:14 -0700667 mProtectedNetworks = new ArrayList<Integer>();
668 int[] protectedNetworks = context.getResources().getIntArray(
669 com.android.internal.R.array.config_protectedNetworks);
670 for (int p : protectedNetworks) {
671 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
672 mProtectedNetworks.add(p);
673 } else {
674 if (DBG) loge("Ignoring protectedNetwork " + p);
675 }
676 }
677
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700678 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
679 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700680
Robert Greenwaltfab501672014-07-23 11:44:01 -0700681 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800682
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700683 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
684
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700685 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700686 IntentFilter intentFilter = new IntentFilter();
687 intentFilter.addAction(Intent.ACTION_USER_STARTING);
688 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
689 mContext.registerReceiverAsUser(
690 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900691
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700692 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700693 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700694 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700695 } catch (RemoteException e) {
696 loge("Error registering observer :" + e);
697 }
698
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700699 if (DBG) {
700 mInetLog = new ArrayList();
701 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700702
Erik Klineda4bfa82015-04-30 12:58:40 +0900703 mSettingsObserver = new SettingsObserver(mContext, mHandler);
704 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800705
John Spurlockbf991a82013-06-24 14:20:23 -0400706 mDataConnectionStats = new DataConnectionStats(mContext);
707 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400708
Jason Monkdecd2952013-10-10 14:02:51 -0400709 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700710
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400711 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700713
Erik Klineda4bfa82015-04-30 12:58:40 +0900714 private NetworkRequest createInternetRequestForTransport(int transportType) {
715 NetworkCapabilities netCap = new NetworkCapabilities();
716 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
717 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
718 if (transportType > -1) {
719 netCap.addTransportType(transportType);
720 }
721 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
722 }
723
724 private void handleMobileDataAlwaysOn() {
725 final boolean enable = (Settings.Global.getInt(
726 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
727 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
728 if (enable == isEnabled) {
729 return; // Nothing to do.
730 }
731
732 if (enable) {
733 handleRegisterNetworkRequest(new NetworkRequestInfo(
734 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
735 } else {
736 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
737 }
738 }
739
740 private void registerSettingsCallbacks() {
741 // Watch for global HTTP proxy changes.
742 mSettingsObserver.observe(
743 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
744 EVENT_APPLY_GLOBAL_HTTP_PROXY);
745
746 // Watch for whether or not to keep mobile data always on.
747 mSettingsObserver.observe(
748 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
749 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
750 }
751
Robert Greenwalt34524f02014-05-18 16:22:10 -0700752 private synchronized int nextNetworkRequestId() {
753 return mNextNetworkRequestId++;
754 }
755
Paul Jensen31a94f42015-02-13 14:18:39 -0500756 private int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400757 synchronized (mNetworkForNetId) {
758 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
759 int netId = mNextNetId;
760 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
761 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500762 if (!mNetIdInUse.get(netId)) {
763 mNetIdInUse.put(netId, true);
764 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400765 }
766 }
767 }
768 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700769 }
770
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800771 private NetworkState getFilteredNetworkState(int networkType, int uid) {
772 NetworkInfo info = null;
773 LinkProperties lp = null;
774 NetworkCapabilities nc = null;
775 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800776 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800777
778 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
779 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
780 if (nai != null) {
781 synchronized (nai) {
782 info = new NetworkInfo(nai.networkInfo);
783 lp = new LinkProperties(nai.linkProperties);
784 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400785 // Network objects are outwardly immutable so there is no point to duplicating.
786 // Duplicating also precludes sharing socket factories and connection pools.
787 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800788 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800789 }
790 info.setType(networkType);
791 } else {
792 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
793 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
794 info.setIsAvailable(true);
795 lp = new LinkProperties();
796 nc = new NetworkCapabilities();
797 network = null;
798 }
799 info = getFilteredNetworkInfo(info, lp, uid);
800 }
801
Jeff Sharkey32566012014-12-02 18:30:14 -0800802 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400803 }
804
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800805 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
806 if (network == null) {
807 return null;
808 }
809 synchronized (mNetworkForNetId) {
810 return mNetworkForNetId.get(network.netId);
811 }
812 };
813
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900814 private Network[] getVpnUnderlyingNetworks(int uid) {
815 if (!mLockdownEnabled) {
816 int user = UserHandle.getUserId(uid);
817 synchronized (mVpns) {
818 Vpn vpn = mVpns.get(user);
819 if (vpn != null && vpn.appliesToUid(uid)) {
820 return vpn.getUnderlyingNetworks();
821 }
822 }
823 }
824 return null;
825 }
826
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800827 private NetworkState getUnfilteredActiveNetworkState(int uid) {
828 NetworkInfo info = null;
829 LinkProperties lp = null;
830 NetworkCapabilities nc = null;
831 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800832 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800833
834 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800835
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900836 final Network[] networks = getVpnUnderlyingNetworks(uid);
837 if (networks != null) {
838 // getUnderlyingNetworks() returns:
839 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
840 // empty array => the VPN explicitly said "no default network".
841 // non-empty array => the VPN specified one or more default networks; we use the
842 // first one.
843 if (networks.length > 0) {
844 nai = getNetworkAgentInfoForNetwork(networks[0]);
845 } else {
846 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800847 }
848 }
849
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800850 if (nai != null) {
851 synchronized (nai) {
852 info = new NetworkInfo(nai.networkInfo);
853 lp = new LinkProperties(nai.linkProperties);
854 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400855 // Network objects are outwardly immutable so there is no point to duplicating.
856 // Duplicating also precludes sharing socket factories and connection pools.
857 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800858 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800859 }
860 }
861
Jeff Sharkey32566012014-12-02 18:30:14 -0800862 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400863 }
864
865 /**
866 * Check if UID should be blocked from using the network with the given LinkProperties.
867 */
868 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700869 final boolean networkCostly;
870 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700871
Robert Greenwalt12e67352014-05-13 21:41:06 -0700872 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700873 synchronized (mRulesLock) {
874 networkCostly = mMeteredIfaces.contains(iface);
875 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700876 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700877
Amith Yamasani15e472352015-04-24 19:06:07 -0700878 if ((uidRules & RULE_REJECT_ALL) != 0
879 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700880 return true;
881 }
882
883 // no restrictive rules; network is visible
884 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700885 }
886
887 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700888 * Return a filtered {@link NetworkInfo}, potentially marked
889 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800890 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700891 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800892 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
893 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400894 // network is blocked; clone and override state
895 info = new NetworkInfo(info);
896 info.setDetailedState(DetailedState.BLOCKED, null, null);
Erik Kline338317e2015-01-19 16:19:09 +0900897 if (DBG) {
898 log("returning Blocked NetworkInfo for ifname=" +
899 lp.getInterfaceName() + ", uid=" + uid);
900 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700901 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800902 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700903 info = mLockdownTracker.augmentNetworkInfo(info);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700904 if (DBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700905 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700906 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700907 }
908
909 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 * Return NetworkInfo for the active (i.e., connected) network interface.
911 * It is assumed that at most one network is active at a time. If more
912 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700913 * @return the info for the active network, or {@code null} if none is
914 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700916 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700918 enforceAccessPermission();
919 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800920 NetworkState state = getUnfilteredActiveNetworkState(uid);
921 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 }
923
Paul Jensen31a94f42015-02-13 14:18:39 -0500924 @Override
925 public Network getActiveNetwork() {
926 enforceAccessPermission();
927 final int uid = Binder.getCallingUid();
928 final int user = UserHandle.getUserId(uid);
929 int vpnNetId = NETID_UNSET;
930 synchronized (mVpns) {
931 final Vpn vpn = mVpns.get(user);
932 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
933 }
934 NetworkAgentInfo nai;
935 if (vpnNetId != NETID_UNSET) {
936 synchronized (mNetworkForNetId) {
937 nai = mNetworkForNetId.get(vpnNetId);
938 }
939 if (nai != null) return nai.network;
940 }
941 nai = getDefaultNetwork();
942 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
943 return nai != null ? nai.network : null;
944 }
945
Wink Saville948282b2013-08-29 08:55:16 -0700946 /**
947 * Find the first Provisioning network.
948 *
949 * @return NetworkInfo or null if none.
950 */
951 private NetworkInfo getProvisioningNetworkInfo() {
952 enforceAccessPermission();
953
954 // Find the first Provisioning Network
955 NetworkInfo provNi = null;
956 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville67c38212013-09-05 12:02:25 -0700957 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -0700958 provNi = ni;
959 break;
960 }
961 }
962 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
963 return provNi;
964 }
965
966 /**
967 * Find the first Provisioning network or the ActiveDefaultNetwork
968 * if there is no Provisioning network
969 *
970 * @return NetworkInfo or null if none.
971 */
972 @Override
973 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
974 enforceAccessPermission();
975
976 NetworkInfo provNi = getProvisioningNetworkInfo();
977 if (provNi == null) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800978 provNi = getActiveNetworkInfo();
Wink Saville948282b2013-08-29 08:55:16 -0700979 }
980 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
981 return provNi;
982 }
983
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700984 public NetworkInfo getActiveNetworkInfoUnfiltered() {
985 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800986 final int uid = Binder.getCallingUid();
987 NetworkState state = getUnfilteredActiveNetworkState(uid);
988 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700989 }
990
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700991 @Override
992 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
993 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800994 NetworkState state = getUnfilteredActiveNetworkState(uid);
995 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700996 }
997
998 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 public NetworkInfo getNetworkInfo(int networkType) {
1000 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001001 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001002 if (getVpnUnderlyingNetworks(uid) != null) {
1003 // A VPN is active, so we may need to return one of its underlying networks. This
1004 // information is not available in LegacyTypeTracker, so we have to get it from
1005 // getUnfilteredActiveNetworkState.
1006 NetworkState state = getUnfilteredActiveNetworkState(uid);
1007 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1008 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1009 }
1010 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001011 NetworkState state = getFilteredNetworkState(networkType, uid);
1012 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 }
1014
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001015 @Override
1016 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1017 enforceAccessPermission();
1018 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001019 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001020 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1021 if (nai != null) {
1022 synchronized (nai) {
1023 info = new NetworkInfo(nai.networkInfo);
1024 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001025 }
1026 }
1027 return info;
1028 }
1029
1030 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 public NetworkInfo[] getAllNetworkInfo() {
1032 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001033 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001034 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1035 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001036 NetworkInfo info = getNetworkInfo(networkType);
1037 if (info != null) {
1038 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001041 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 }
1043
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001044 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001045 public Network getNetworkForType(int networkType) {
1046 enforceAccessPermission();
1047 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001048 NetworkState state = getFilteredNetworkState(networkType, uid);
1049 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1050 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001051 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001052 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001053 }
1054
1055 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001056 public Network[] getAllNetworks() {
1057 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001058 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001059 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001060 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001061 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001062 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001063 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001064 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001065 }
1066
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001067 private NetworkCapabilities getNetworkCapabilitiesAndValidation(NetworkAgentInfo nai) {
1068 if (nai != null) {
1069 synchronized (nai) {
1070 if (nai.created) {
1071 NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001072 if (nai.lastValidated) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001073 nc.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1074 } else {
1075 nc.removeCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1076 }
1077 return nc;
1078 }
1079 }
1080 }
1081 return null;
1082 }
1083
1084 @Override
1085 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1086 // The basic principle is: if an app's traffic could possibly go over a
1087 // network, without the app doing anything multinetwork-specific,
1088 // (hence, by "default"), then include that network's capabilities in
1089 // the array.
1090 //
1091 // In the normal case, app traffic only goes over the system's default
1092 // network connection, so that's the only network returned.
1093 //
1094 // With a VPN in force, some app traffic may go into the VPN, and thus
1095 // over whatever underlying networks the VPN specifies, while other app
1096 // traffic may go over the system default network (e.g.: a split-tunnel
1097 // VPN, or an app disallowed by the VPN), so the set of networks
1098 // returned includes the VPN's underlying networks and the system
1099 // default.
1100 enforceAccessPermission();
1101
1102 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1103
1104 NetworkAgentInfo nai = getDefaultNetwork();
1105 NetworkCapabilities nc = getNetworkCapabilitiesAndValidation(getDefaultNetwork());
1106 if (nc != null) {
1107 result.put(nai.network, nc);
1108 }
1109
1110 if (!mLockdownEnabled) {
1111 synchronized (mVpns) {
1112 Vpn vpn = mVpns.get(userId);
1113 if (vpn != null) {
1114 Network[] networks = vpn.getUnderlyingNetworks();
1115 if (networks != null) {
1116 for (Network network : networks) {
1117 nai = getNetworkAgentInfoForNetwork(network);
1118 nc = getNetworkCapabilitiesAndValidation(nai);
1119 if (nc != null) {
1120 result.put(nai.network, nc);
1121 }
1122 }
1123 }
1124 }
1125 }
1126 }
1127
1128 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1129 out = result.values().toArray(out);
1130 return out;
1131 }
1132
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001133 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001134 public boolean isNetworkSupported(int networkType) {
1135 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001136 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001137 }
1138
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001139 /**
1140 * Return LinkProperties for the active (i.e., connected) default
1141 * network interface. It is assumed that at most one default network
1142 * is active at a time. If more than one is active, it is indeterminate
1143 * which will be returned.
1144 * @return the ip properties for the active network, or {@code null} if
1145 * none is active
1146 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001147 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001148 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001149 enforceAccessPermission();
1150 final int uid = Binder.getCallingUid();
1151 NetworkState state = getUnfilteredActiveNetworkState(uid);
1152 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001153 }
1154
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001155 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001156 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001157 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001158 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1159 if (nai != null) {
1160 synchronized (nai) {
1161 return new LinkProperties(nai.linkProperties);
1162 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001163 }
1164 return null;
1165 }
1166
Robert Greenwalt12e67352014-05-13 21:41:06 -07001167 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001168 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001169 public LinkProperties getLinkProperties(Network network) {
1170 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001171 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001172 if (nai != null) {
1173 synchronized (nai) {
1174 return new LinkProperties(nai.linkProperties);
1175 }
1176 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001177 return null;
1178 }
1179
1180 @Override
1181 public NetworkCapabilities getNetworkCapabilities(Network network) {
1182 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001183 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001184 if (nai != null) {
1185 synchronized (nai) {
Sanket Padawe7094d222015-05-01 16:55:00 -07001186 NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
1187 if (nai.lastValidated) {
1188 nc.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1189 } else {
1190 nc.removeCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1191 }
1192 return nc;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001193 }
1194 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001195 return null;
1196 }
1197
1198 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001199 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001200 // Require internal since we're handing out IMSI details
1201 enforceConnectivityInternalPermission();
1202
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001203 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001204 for (Network network : getAllNetworks()) {
1205 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1206 if (nai != null) {
1207 synchronized (nai) {
1208 final String subscriberId = (nai.networkMisc != null)
1209 ? nai.networkMisc.subscriberId : null;
1210 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1211 nai.networkCapabilities, network, subscriberId, null));
1212 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001213 }
1214 }
1215 return result.toArray(new NetworkState[result.size()]);
1216 }
1217
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001218 @Override
1219 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1220 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001221 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001222 final long token = Binder.clearCallingIdentity();
1223 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001224 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1225 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001226 try {
1227 return mPolicyManager.getNetworkQuotaInfo(state);
1228 } catch (RemoteException e) {
1229 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001230 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001231 return null;
1232 } finally {
1233 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001234 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001235 }
1236
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001237 @Override
1238 public boolean isActiveNetworkMetered() {
1239 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001240 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001241 final long token = Binder.clearCallingIdentity();
1242 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001243 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001244 } finally {
1245 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001246 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001247 }
1248
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001249 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1250 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1251 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001252 try {
1253 return mPolicyManager.isNetworkMetered(state);
1254 } catch (RemoteException e) {
1255 }
1256 }
1257 return false;
1258 }
1259
Jeff Sharkey216c1812012-08-05 14:29:23 -07001260 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1261 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001262 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001263 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001264 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001265 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001266 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001267
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001268 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 * Ensure that a network route exists to deliver traffic to the specified
1270 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001271 * @param networkType the type of the network over which traffic to the
1272 * specified host is to be routed
1273 * @param hostAddress the IP address of the host to which the route is
1274 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 * @return {@code true} on success, {@code false} on failure
1276 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001277 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001279 if (mProtectedNetworks.contains(networkType)) {
1280 enforceConnectivityInternalPermission();
1281 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001282
Chad Brubakerc0234532014-02-14 13:24:29 -08001283 InetAddress addr;
1284 try {
1285 addr = InetAddress.getByAddress(hostAddress);
1286 } catch (UnknownHostException e) {
1287 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1288 return false;
1289 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001292 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 return false;
1294 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001295
1296 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1297 if (nai == null) {
1298 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1299 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1300 } else {
1301 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1302 }
1303 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001304 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001305
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001306 DetailedState netState;
1307 synchronized (nai) {
1308 netState = nai.networkInfo.getDetailedState();
1309 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001310
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001311 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001312 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001313 log("requestRouteToHostAddress on down network "
1314 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001315 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001316 }
1317 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001319
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001320 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001321 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001322 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001323 LinkProperties lp;
1324 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001325 synchronized (nai) {
1326 lp = nai.linkProperties;
1327 netId = nai.network.netId;
1328 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001329 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001330 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1331 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001332 } finally {
1333 Binder.restoreCallingIdentity(token);
1334 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001335 }
1336
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001337 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001338 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001339 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001340 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001341 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001342 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001343 if (bestRoute.getGateway().equals(addr)) {
1344 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001345 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001346 } else {
1347 // if we will connect to this through another route, add a direct route
1348 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001349 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001350 }
1351 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001352 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001353 try {
1354 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1355 } catch (Exception e) {
1356 // never crash - catch them all
1357 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001358 return false;
1359 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001360 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 }
1362
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001363 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1364 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001365 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001366 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001367 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001368 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001369 }
1370
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001371 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001372 // skip update when we've already applied rules
1373 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1374 if (oldRules == uidRules) return;
1375
1376 mUidRules.put(uid, uidRules);
1377 }
1378
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001379 // TODO: notify UID when it has requested targeted updates
1380 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001381
1382 @Override
1383 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001384 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001385 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001386 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001387 }
1388
1389 synchronized (mRulesLock) {
1390 mMeteredIfaces.clear();
1391 for (String iface : meteredIfaces) {
1392 mMeteredIfaces.add(iface);
1393 }
1394 }
1395 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001396
1397 @Override
1398 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1399 // caller is NPMS, since we only register with them
1400 if (LOGD_RULES) {
1401 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1402 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001403 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001404 };
1405
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001406 private void enforceInternetPermission() {
1407 mContext.enforceCallingOrSelfPermission(
1408 android.Manifest.permission.INTERNET,
1409 "ConnectivityService");
1410 }
1411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001413 mContext.enforceCallingOrSelfPermission(
1414 android.Manifest.permission.ACCESS_NETWORK_STATE,
1415 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 }
1417
1418 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001419 mContext.enforceCallingOrSelfPermission(
1420 android.Manifest.permission.CHANGE_NETWORK_STATE,
1421 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 }
1423
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001424 private void enforceTetherAccessPermission() {
1425 mContext.enforceCallingOrSelfPermission(
1426 android.Manifest.permission.ACCESS_NETWORK_STATE,
1427 "ConnectivityService");
1428 }
1429
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001430 private void enforceConnectivityInternalPermission() {
1431 mContext.enforceCallingOrSelfPermission(
1432 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1433 "ConnectivityService");
1434 }
1435
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001436 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001437 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001438 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001439 }
1440
1441 private void sendInetConditionBroadcast(NetworkInfo info) {
1442 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1443 }
1444
Wink Saville628b0852011-08-04 15:01:58 -07001445 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001446 if (mLockdownTracker != null) {
1447 info = mLockdownTracker.augmentNetworkInfo(info);
1448 }
1449
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001450 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001451 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001452 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 if (info.isFailover()) {
1454 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1455 info.setFailover(false);
1456 }
1457 if (info.getReason() != null) {
1458 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1459 }
1460 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001461 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1462 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001464 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001465 return intent;
1466 }
1467
1468 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1469 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1470 }
1471
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001472 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001473 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1474 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1475 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001476 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001477 final long ident = Binder.clearCallingIdentity();
1478 try {
1479 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1480 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1481 } finally {
1482 Binder.restoreCallingIdentity(ident);
1483 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001484 }
1485
Mike Lockwood0f79b542009-08-14 14:18:49 -04001486 private void sendStickyBroadcast(Intent intent) {
1487 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001488 if (!mSystemReady) {
1489 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001490 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001491 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001492 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001493 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001494 }
1495
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001496 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001497 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1498 final IBatteryStats bs = BatteryStatsService.getService();
1499 try {
1500 NetworkInfo ni = intent.getParcelableExtra(
1501 ConnectivityManager.EXTRA_NETWORK_INFO);
1502 bs.noteConnectivityChanged(intent.getIntExtra(
1503 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1504 ni != null ? ni.getState().toString() : "?");
1505 } catch (RemoteException e) {
1506 }
1507 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001508 try {
1509 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1510 } finally {
1511 Binder.restoreCallingIdentity(ident);
1512 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001513 }
1514 }
1515
1516 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001517 loadGlobalProxy();
1518
Mike Lockwood0f79b542009-08-14 14:18:49 -04001519 synchronized(this) {
1520 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001521 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001522 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001523 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001524 }
1525 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001526 // load the global proxy at startup
1527 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001528
1529 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1530 // for user to unlock device.
1531 if (!updateLockdownVpn()) {
1532 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1533 mContext.registerReceiver(mUserPresentReceiver, filter);
1534 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001535
Erik Klineda4bfa82015-04-30 12:58:40 +09001536 // Configure whether mobile data is always on.
1537 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1538
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001539 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001540
1541 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 }
1543
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001544 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1545 @Override
1546 public void onReceive(Context context, Intent intent) {
1547 // Try creating lockdown tracker, since user present usually means
1548 // unlocked keystore.
1549 if (updateLockdownVpn()) {
1550 mContext.unregisterReceiver(this);
1551 }
1552 }
1553 };
1554
Wink Savilled747cbc2013-08-07 16:22:47 -07001555 /** @hide */
1556 @Override
1557 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
1558 enforceConnectivityInternalPermission();
1559 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
Robert Greenwalt12e67352014-05-13 21:41:06 -07001560// mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
Wink Savilled747cbc2013-08-07 16:22:47 -07001561 }
1562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001564 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001565 *
1566 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001567 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001568 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001569 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1570 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001571
1572 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001573 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001574
Robert Greenwalt7b816022014-04-18 15:25:25 -07001575 if (networkAgent.networkCapabilities.hasTransport(
1576 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001577 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1578 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001579 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001580 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001581 } else if (networkAgent.networkCapabilities.hasTransport(
1582 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001583 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1584 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinskie08af192015-03-25 16:42:59 -07001585 5);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001586 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001587 } else {
1588 // do not track any other networks
1589 timeout = 0;
1590 }
1591
Robert Greenwalt7b816022014-04-18 15:25:25 -07001592 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001593 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001594 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001595 } catch (Exception e) {
1596 // You shall not crash!
1597 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001598 }
1599 }
1600 }
1601
1602 /**
1603 * Remove data activity tracking when network disconnects.
1604 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001605 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1606 final String iface = networkAgent.linkProperties.getInterfaceName();
1607 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001608
Robert Greenwalt7b816022014-04-18 15:25:25 -07001609 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1610 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001611 try {
1612 // the call fails silently if no idletimer setup for this interface
1613 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001614 } catch (Exception e) {
1615 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001616 }
1617 }
1618 }
1619
1620 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001621 * Reads the network specific MTU size from reources.
1622 * and set it on it's iface.
1623 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001624 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1625 final String iface = newLp.getInterfaceName();
1626 final int mtu = newLp.getMtu();
1627 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1628 if (VDBG) log("identical MTU - not setting");
1629 return;
1630 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001631
Robert Greenwalt43074032014-08-15 17:53:05 -07001632 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001633 loge("Unexpected mtu value: " + mtu + ", " + iface);
1634 return;
1635 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001636
w1997615afd812014-08-05 15:18:11 -07001637 // Cannot set MTU without interface name
1638 if (TextUtils.isEmpty(iface)) {
1639 loge("Setting MTU size with null iface.");
1640 return;
1641 }
1642
Robert Greenwalt7b816022014-04-18 15:25:25 -07001643 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001644 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001645 mNetd.setMtu(iface, mtu);
1646 } catch (Exception e) {
1647 Slog.e(TAG, "exception in setMtu()" + e);
1648 }
1649 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001650
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001651 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Irfan Sheriffd649c122010-06-09 15:39:36 -07001652
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001653 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1654 if (isDefaultNetwork(nai) == false) {
1655 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001656 }
1657
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001658 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1659 String[] values = null;
1660 if (tcpBufferSizes != null) {
1661 values = tcpBufferSizes.split(",");
1662 }
1663
1664 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001665 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001666 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1667 values = tcpBufferSizes.split(",");
1668 }
1669
1670 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1671
1672 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001673 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001674
1675 final String prefix = "/sys/kernel/ipv4/tcp_";
1676 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1677 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1678 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1679 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1680 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1681 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1682 mCurrentTcpBufferSizes = tcpBufferSizes;
1683 } catch (IOException e) {
1684 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001685 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001686
1687 final String defaultRwndKey = "net.tcp.default_init_rwnd";
1688 int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
1689 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
1690 Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
1691 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1692 if (rwndValue != 0) {
1693 SystemProperties.set(sysctlKey, rwndValue.toString());
1694 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001695 }
1696
Mattias Falk8b47b362011-08-23 14:15:13 +02001697 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001698 /*
1699 * Tell the VMs to toss their DNS caches
1700 */
1701 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1702 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001703 /*
1704 * Connectivity events can happen before boot has completed ...
1705 */
1706 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001707 final long ident = Binder.clearCallingIdentity();
1708 try {
1709 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1710 } finally {
1711 Binder.restoreCallingIdentity(ident);
1712 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001713 }
1714
Robert Greenwalt562cc542014-05-15 18:07:26 -07001715 @Override
1716 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001717 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1718 NETWORK_RESTORE_DELAY_PROP_NAME);
1719 if(restoreDefaultNetworkDelayStr != null &&
1720 restoreDefaultNetworkDelayStr.length() != 0) {
1721 try {
1722 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1723 } catch (NumberFormatException e) {
1724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001726 // if the system property isn't set, use the value for the apn type
1727 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1728
1729 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1730 (mNetConfigs[networkType] != null)) {
1731 ret = mNetConfigs[networkType].restoreTime;
1732 }
1733 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 }
1735
1736 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001737 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1738 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001739 if (mContext.checkCallingOrSelfPermission(
1740 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001742 pw.println("Permission Denial: can't dump ConnectivityService " +
1743 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1744 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 return;
1746 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001747
Robert Greenwalta67be032014-05-16 15:49:14 -07001748 pw.println("NetworkFactories for:");
1749 pw.increaseIndent();
1750 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
1751 pw.println(nfi.name);
1752 }
1753 pw.decreaseIndent();
1754 pw.println();
1755
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001756 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1757 pw.print("Active default network: ");
1758 if (defaultNai == null) {
1759 pw.println("none");
1760 } else {
1761 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001763 pw.println();
1764
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001765 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001766 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001767 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1768 pw.println(nai.toString());
1769 pw.increaseIndent();
1770 pw.println("Requests:");
1771 pw.increaseIndent();
1772 for (int i = 0; i < nai.networkRequests.size(); i++) {
1773 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001774 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001775 pw.decreaseIndent();
1776 pw.println("Lingered:");
1777 pw.increaseIndent();
1778 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1779 pw.decreaseIndent();
1780 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001781 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001782 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001783 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001784
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001785 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001786 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001787 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1788 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001789 }
1790 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001791 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001792
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001793 pw.println("mLegacyTypeTracker:");
1794 pw.increaseIndent();
1795 mLegacyTypeTracker.dump(pw);
1796 pw.decreaseIndent();
1797 pw.println();
1798
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001799 synchronized (this) {
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001800 pw.println("NetworkTransitionWakeLock is currently " +
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001801 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1802 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1803 }
1804 pw.println();
1805
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001806 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001807
1808 if (mInetLog != null) {
1809 pw.println();
1810 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001811 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001812 for(int i = 0; i < mInetLog.size(); i++) {
1813 pw.println(mInetLog.get(i));
1814 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001815 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 }
1818
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001819 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001820 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001821 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001822 if (officialNai != null && officialNai.equals(nai)) return true;
1823 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001824 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001825 " - " + nai);
1826 }
1827 return false;
1828 }
1829
Paul Jensenc8b9a742014-09-30 15:37:41 -04001830 private boolean isRequest(NetworkRequest request) {
1831 return mNetworkRequests.get(request).isRequest;
1832 }
1833
Robert Greenwalt42acef32009-08-12 16:08:25 -07001834 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001835 private class NetworkStateTrackerHandler extends Handler {
1836 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001837 super(looper);
1838 }
1839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 @Override
1841 public void handleMessage(Message msg) {
1842 NetworkInfo info;
1843 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001844 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001845 handleAsyncChannelHalfConnect(msg);
1846 break;
1847 }
1848 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1849 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1850 if (nai != null) nai.asyncChannel.disconnect();
1851 break;
1852 }
1853 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1854 handleAsyncChannelDisconnected(msg);
1855 break;
1856 }
1857 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1858 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1859 if (nai == null) {
1860 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1861 } else {
1862 updateCapabilities(nai, (NetworkCapabilities)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07001863 }
1864 break;
1865 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001866 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1867 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1868 if (nai == null) {
1869 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1870 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001871 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001872 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001873 "; created=" + nai.created);
1874 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001875 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001876 synchronized (nai) {
1877 nai.linkProperties = (LinkProperties)msg.obj;
1878 }
Paul Jenseneec75412014-08-04 12:21:19 -04001879 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001880 }
1881 break;
1882 }
1883 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1884 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1885 if (nai == null) {
1886 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1887 break;
1888 }
1889 info = (NetworkInfo) msg.obj;
1890 updateNetworkInfo(nai, info);
1891 break;
1892 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001893 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1894 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1895 if (nai == null) {
1896 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1897 break;
1898 }
1899 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001900 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001901 break;
1902 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001903 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1904 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1905 if (nai == null) {
1906 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1907 break;
1908 }
1909 try {
1910 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001911 } catch (Exception e) {
1912 // Never crash!
1913 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001914 }
1915 break;
1916 }
1917 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1918 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1919 if (nai == null) {
1920 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1921 break;
1922 }
1923 try {
1924 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001925 } catch (Exception e) {
1926 // Never crash!
1927 loge("Exception in removeVpnUidRanges: " + e);
1928 }
1929 break;
1930 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001931 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1932 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1933 if (nai == null) {
1934 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1935 break;
1936 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001937 if (nai.created && !nai.networkMisc.explicitlySelected) {
1938 loge("ERROR: created network explicitly selected.");
1939 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001940 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001941 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07001942 break;
1943 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001944 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001945 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001946 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_VALIDATED")) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001947 boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001948 nai.lastValidated = valid;
Paul Jensenad50a1f2014-09-05 12:06:44 -04001949 if (valid) {
1950 if (DBG) log("Validated " + nai.name());
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09001951 if (!nai.everValidated) {
1952 nai.everValidated = true;
Paul Jensenb10e37f2014-11-25 12:33:08 -05001953 rematchNetworkAndRequests(nai, NascentState.JUST_VALIDATED,
1954 ReapUnvalidatedNetworks.REAP);
1955 // If score has changed, rebroadcast to NetworkFactories. b/17726566
Paul Jensenc8b9a742014-09-30 15:37:41 -04001956 sendUpdatedScoreToFactories(nai);
1957 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001958 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001959 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07001960 // Let the NetworkAgent know the state of its network
1961 nai.asyncChannel.sendMessage(
1962 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
1963 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
1964 0, null);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001965
1966 // TODO: trigger a NetworkCapabilities update so that the dialog can know
1967 // that the network is now validated and close itself.
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001968 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001969 break;
1970 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001971 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001972 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001973 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
1974 handleLingerComplete(nai);
1975 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001976 break;
1977 }
Paul Jensen869868be2014-05-15 10:33:05 -04001978 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001979 if (msg.arg1 == 0) {
1980 setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
1981 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04001982 NetworkAgentInfo nai = null;
1983 synchronized (mNetworkForNetId) {
1984 nai = mNetworkForNetId.get(msg.arg2);
1985 }
1986 if (nai == null) {
1987 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
1988 break;
1989 }
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001990 setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
1991 nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
Paul Jensen869868be2014-05-15 10:33:05 -04001992 }
Paul Jensen869868be2014-05-15 10:33:05 -04001993 break;
1994 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001995 }
1996 }
1997 }
1998
Paul Jensen0cc17322014-11-25 15:26:53 -05001999 // Cancel any lingering so the linger timeout doesn't teardown a network.
2000 // This should be called when a network begins satisfying a NetworkRequest.
2001 // Note: depending on what state the NetworkMonitor is in (e.g.,
2002 // if it's awaiting captive portal login, or if validation failed), this
2003 // may trigger a re-evaluation of the network.
2004 private void unlinger(NetworkAgentInfo nai) {
2005 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05002006 // If network has never been validated, it cannot have been lingered, so don't bother
2007 // needlessly triggering a re-evaluation.
2008 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05002009 nai.networkLingered.clear();
2010 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2011 }
2012
Robert Greenwalt7b816022014-04-18 15:25:25 -07002013 private void handleAsyncChannelHalfConnect(Message msg) {
2014 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002015 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002016 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2017 if (VDBG) log("NetworkFactory connected");
2018 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002019 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002020 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002021 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002022 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002023 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002024 }
2025 } else {
2026 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002027 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002028 }
2029 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2030 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2031 if (VDBG) log("NetworkAgent connected");
2032 // A network agent has requested a connection. Establish the connection.
2033 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2034 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2035 } else {
2036 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002037 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002038 if (nai != null) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002039 synchronized (mNetworkForNetId) {
2040 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002041 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002042 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002043 // Just in case.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07002044 mLegacyTypeTracker.remove(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002045 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002046 }
2047 }
2048 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002049
Robert Greenwalt7b816022014-04-18 15:25:25 -07002050 private void handleAsyncChannelDisconnected(Message msg) {
2051 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2052 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002053 if (DBG) {
2054 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2055 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002056 // A network agent has disconnected.
Paul Jenseneec75412014-08-04 12:21:19 -04002057 if (nai.created) {
2058 // Tell netd to clean up the configuration for this network
2059 // (routing rules, DNS, etc).
2060 try {
2061 mNetd.removeNetwork(nai.network.netId);
2062 } catch (Exception e) {
2063 loge("Exception removing network: " + e);
2064 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002065 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07002066 // TODO - if we move the logic to the network agent (have them disconnect
2067 // because they lost all their requests or because their score isn't good)
2068 // then they would disconnect organically, report their new state and then
2069 // disconnect the channel.
2070 if (nai.networkInfo.isConnected()) {
2071 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2072 null, null);
2073 }
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002074 if (isDefaultNetwork(nai)) {
2075 mDefaultInetConditionPublished = 0;
2076 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002077 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002078 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002079 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002080 mNetworkAgentInfos.remove(msg.replyTo);
2081 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07002082 mLegacyTypeTracker.remove(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002083 synchronized (mNetworkForNetId) {
2084 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002085 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002086 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002087 // Since we've lost the network, go through all the requests that
2088 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002089 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04002090 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07002091 for (int i = 0; i < nai.networkRequests.size(); i++) {
2092 NetworkRequest request = nai.networkRequests.valueAt(i);
2093 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2094 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002095 if (DBG) {
2096 log("Checking for replacement network to handle request " + request );
2097 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002098 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002099 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002100 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05002101 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2102 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002103 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002104 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002105 alternative = existing;
2106 }
2107 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002108 if (alternative != null) {
2109 if (DBG) log(" found replacement in " + alternative.name());
2110 if (!toActivate.contains(alternative)) {
2111 toActivate.add(alternative);
2112 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002113 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002114 }
2115 }
2116 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2117 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002118 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002119 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002120 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002121 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002122 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002123 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2124 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002125 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002126 }
Maunik Shah4b647f42015-03-30 11:36:42 +05302127 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2128 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002129 }
2130
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002131 // If this method proves to be too slow then we can maintain a separate
2132 // pendingIntent => NetworkRequestInfo map.
2133 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2134 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2135 Intent intent = pendingIntent.getIntent();
2136 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2137 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2138 if (existingPendingIntent != null &&
2139 existingPendingIntent.getIntent().filterEquals(intent)) {
2140 return entry.getValue();
2141 }
2142 }
2143 return null;
2144 }
2145
2146 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2147 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2148
2149 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2150 if (existingRequest != null) { // remove the existing request.
2151 if (DBG) log("Replacing " + existingRequest.request + " with "
2152 + nri.request + " because their intents matched.");
2153 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2154 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002155 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002156 }
2157
Erik Klineda4bfa82015-04-30 12:58:40 +09002158 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002159 mNetworkRequests.put(nri.request, nri);
2160
Paul Jensen0cc17322014-11-25 15:26:53 -05002161 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2162
Robert Greenwalt9258c642014-03-26 16:47:06 -07002163 // Check for the best currently alive network that satisfies this request
2164 NetworkAgentInfo bestNetwork = null;
2165 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002166 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002167 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002168 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002169 if (!nri.isRequest) {
2170 // Not setting bestNetwork here as a listening NetworkRequest may be
2171 // satisfied by multiple Networks. Instead the request is added to
2172 // each satisfying Network and notified about each.
2173 network.addRequest(nri.request);
2174 notifyNetworkCallback(network, nri);
2175 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002176 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002177 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002178 }
2179 }
2180 }
2181 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002182 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002183 unlinger(bestNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07002184 bestNetwork.addRequest(nri.request);
Robert Greenwalt2d370702014-06-03 17:22:11 -07002185 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002186 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002187 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002188 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2189 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002190 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002191
Lorenzo Colittia793a672014-07-31 23:20:17 +09002192 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002193 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002194 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002195 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002196 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002197 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002198 }
2199 }
2200 }
2201
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002202 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2203 int callingUid) {
2204 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2205 if (nri != null) {
2206 handleReleaseNetworkRequest(nri.request, callingUid);
2207 }
2208 }
2209
Paul Jensen99364842014-12-09 11:43:45 -05002210 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2211 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2212 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2213 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2214 private boolean unneeded(NetworkAgentInfo nai) {
2215 if (!nai.created || nai.isVPN()) return false;
2216 boolean unneeded = true;
2217 if (nai.everValidated) {
2218 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2219 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2220 try {
2221 if (isRequest(nr)) unneeded = false;
2222 } catch (Exception e) {
2223 loge("Request " + nr + " not found in mNetworkRequests.");
2224 loge(" it came from request list of " + nai.name());
2225 }
2226 }
2227 } else {
2228 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2229 // If this Network is already the highest scoring Network for a request, or if
2230 // there is hope for it to become one if it validated, then it is needed.
2231 if (nri.isRequest && nai.satisfies(nri.request) &&
2232 (nai.networkRequests.get(nri.request.requestId) != null ||
2233 // Note that this catches two important cases:
2234 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2235 // is currently satisfying the request. This is desirable when
2236 // cellular ends up validating but WiFi does not.
2237 // 2. Unvalidated WiFi will not be reaped when validated cellular
2238 // is currently satsifying the request. This is desirable when
2239 // WiFi ends up validating and out scoring cellular.
2240 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2241 nai.getCurrentScoreAsValidated())) {
2242 unneeded = false;
2243 break;
2244 }
2245 }
2246 }
2247 return unneeded;
2248 }
2249
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002250 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2251 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002252 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002253 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002254 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2255 return;
2256 }
2257 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002258 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002259 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002260 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002261 // Find all networks that are satisfying this request and remove the request
2262 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002263 // TODO - it's my understanding that for a request there is only a single
2264 // network satisfying it, so this loop is wasteful
2265 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002266 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2267 if (nai.networkRequests.get(nri.request.requestId) != null) {
2268 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002269 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002270 log(" Removing from current network " + nai.name() +
2271 ", leaving " + nai.networkRequests.size() +
2272 " requests.");
2273 }
Paul Jensen99364842014-12-09 11:43:45 -05002274 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002275 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002276 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002277 } else {
2278 // suspect there should only be one pass through here
2279 // but if any were kept do the check below
2280 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002281 }
2282 }
2283 }
2284
Robert Greenwalt51481852015-01-08 14:43:31 -08002285 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2286 if (nai != null) {
2287 mNetworkForRequestId.remove(nri.request.requestId);
2288 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002289 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002290 // that a network connected to serve it, even though the network was already
2291 // connected. Now that this request has gone away, we might have to pretend
2292 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002293 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002294 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2295 boolean doRemove = true;
2296 if (wasKept) {
2297 // check if any of the remaining requests for this network are for the
2298 // same legacy type - if so, don't remove the nai
2299 for (int i = 0; i < nai.networkRequests.size(); i++) {
2300 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2301 if (otherRequest.legacyType == nri.request.legacyType &&
2302 isRequest(otherRequest)) {
2303 if (DBG) log(" still have other legacy request - leaving");
2304 doRemove = false;
2305 }
2306 }
2307 }
2308
2309 if (doRemove) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002310 mLegacyTypeTracker.remove(nri.request.legacyType, nai);
2311 }
2312 }
2313
Robert Greenwalta67be032014-05-16 15:49:14 -07002314 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002315 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2316 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002317 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002318 } else {
2319 // listens don't have a singular affectedNetwork. Check all networks to see
2320 // if this listen request applies and remove it.
2321 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2322 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002323 }
2324 }
2325 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2326 }
2327 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002328
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002329 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2330 enforceConnectivityInternalPermission();
2331 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2332 accept ? 1 : 0, always ? 1: 0, network));
2333 }
2334
2335 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2336 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2337 " accept=" + accept + " always=" + always);
2338
2339 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2340 if (nai == null) {
2341 // Nothing to do.
2342 return;
2343 }
2344
2345 if (nai.everValidated) {
2346 // The network validated while the dialog box was up. Don't make any changes. There's a
2347 // TODO in the dialog code to make it go away if the network validates; once that's
2348 // implemented, taking action here will be confusing.
2349 return;
2350 }
2351
2352 if (!nai.networkMisc.explicitlySelected) {
2353 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2354 }
2355
2356 if (accept != nai.networkMisc.acceptUnvalidated) {
2357 int oldScore = nai.getCurrentScore();
2358 nai.networkMisc.acceptUnvalidated = accept;
2359 rematchAllNetworksAndRequests(nai, oldScore);
2360 sendUpdatedScoreToFactories(nai);
2361 }
2362
2363 if (always) {
2364 nai.asyncChannel.sendMessage(
2365 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2366 }
2367
2368 // TODO: should we also disconnect from the network if accept is false?
2369 }
2370
2371 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
2372 mHandler.sendMessageDelayed(
2373 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2374 PROMPT_UNVALIDATED_DELAY_MS);
2375 }
2376
2377 private void handlePromptUnvalidated(Network network) {
2378 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2379
2380 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2381 // we haven't already been told to switch to it regardless of whether it validated or not.
2382 if (nai == null || nai.everValidated ||
2383 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2384 return;
2385 }
2386
2387 // TODO: What should we do if we've already switched to this network because we had no
2388 // better option? There are two obvious alternatives.
2389 //
2390 // 1. Decide that there's no point prompting because this is our only usable network.
2391 // However, because we didn't prompt, if later on a validated network comes along, we'll
2392 // either a) silently switch to it - bad if the user wanted to connect to stay on this
2393 // unvalidated network - or b) prompt the user at that later time - bad because the user
2394 // might not understand why they are now being prompted.
2395 //
2396 // 2. Always prompt the user, even if we have no other network to use. The user could then
2397 // try to find an alternative network to join (remember, if we got here, then the user
2398 // selected this network manually). This is bad because the prompt isn't really very
2399 // useful.
2400 //
2401 // For now we do #1, but we can revisit that later.
2402 if (isDefaultNetwork(nai)) {
2403 return;
2404 }
2405
2406 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
2407 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, network);
2408 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2409 intent.setClassName("com.android.settings",
2410 "com.android.settings.wifi.WifiNoInternetDialog");
2411 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
2412 }
2413
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002414 private class InternalHandler extends Handler {
2415 public InternalHandler(Looper looper) {
2416 super(looper);
2417 }
2418
2419 @Override
2420 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002421 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002422 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002423 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002424 String causedBy = null;
2425 synchronized (ConnectivityService.this) {
2426 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2427 mNetTransitionWakeLock.isHeld()) {
2428 mNetTransitionWakeLock.release();
2429 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002430 } else {
2431 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002432 }
2433 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002434 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2435 log("Failed to find a new network - expiring NetTransition Wakelock");
2436 } else {
2437 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2438 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002439 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002440 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002441 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002442 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002443 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002444 break;
2445 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002446 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002447 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002448 sendStickyBroadcast(intent);
2449 break;
2450 }
Jason Monkdecd2952013-10-10 14:02:51 -04002451 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002452 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002453 break;
2454 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002455 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002456 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2457 break;
2458 }
2459 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2460 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002461 break;
2462 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002463 case EVENT_REGISTER_NETWORK_AGENT: {
2464 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2465 break;
2466 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002467 case EVENT_REGISTER_NETWORK_REQUEST:
2468 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002469 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002470 break;
2471 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002472 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: {
2473 handleRegisterNetworkRequestWithIntent(msg);
2474 break;
2475 }
2476 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2477 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2478 break;
2479 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002480 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002481 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002482 break;
2483 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002484 case EVENT_SET_ACCEPT_UNVALIDATED: {
2485 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2486 break;
2487 }
2488 case EVENT_PROMPT_UNVALIDATED: {
2489 handlePromptUnvalidated((Network) msg.obj);
2490 break;
2491 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002492 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2493 handleMobileDataAlwaysOn();
2494 break;
2495 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002496 case EVENT_SYSTEM_READY: {
2497 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2498 nai.networkMonitor.systemReady = true;
2499 }
2500 break;
2501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 }
2503 }
2504 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002505
2506 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002507 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002508 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002509 if (isTetheringSupported()) {
2510 return mTethering.tether(iface);
2511 } else {
2512 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2513 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002514 }
2515
2516 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002517 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002518 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002519
2520 if (isTetheringSupported()) {
2521 return mTethering.untether(iface);
2522 } else {
2523 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2524 }
2525 }
2526
2527 // javadoc from interface
2528 public int getLastTetherError(String iface) {
2529 enforceTetherAccessPermission();
2530
2531 if (isTetheringSupported()) {
2532 return mTethering.getLastTetherError(iface);
2533 } else {
2534 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2535 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002536 }
2537
2538 // TODO - proper iface API for selection by property, inspection, etc
2539 public String[] getTetherableUsbRegexs() {
2540 enforceTetherAccessPermission();
2541 if (isTetheringSupported()) {
2542 return mTethering.getTetherableUsbRegexs();
2543 } else {
2544 return new String[0];
2545 }
2546 }
2547
2548 public String[] getTetherableWifiRegexs() {
2549 enforceTetherAccessPermission();
2550 if (isTetheringSupported()) {
2551 return mTethering.getTetherableWifiRegexs();
2552 } else {
2553 return new String[0];
2554 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002555 }
2556
Danica Chang6fdd0c62010-08-11 14:54:43 -07002557 public String[] getTetherableBluetoothRegexs() {
2558 enforceTetherAccessPermission();
2559 if (isTetheringSupported()) {
2560 return mTethering.getTetherableBluetoothRegexs();
2561 } else {
2562 return new String[0];
2563 }
2564 }
2565
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002566 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002567 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002568 if (isTetheringSupported()) {
2569 return mTethering.setUsbTethering(enable);
2570 } else {
2571 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2572 }
2573 }
2574
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002575 // TODO - move iface listing, queries, etc to new module
2576 // javadoc from interface
2577 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002578 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002579 return mTethering.getTetherableIfaces();
2580 }
2581
2582 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002583 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002584 return mTethering.getTetheredIfaces();
2585 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002586
Robert Greenwalt5a735062010-03-02 17:25:02 -08002587 public String[] getTetheringErroredIfaces() {
2588 enforceTetherAccessPermission();
2589 return mTethering.getErroredIfaces();
2590 }
2591
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002592 public String[] getTetheredDhcpRanges() {
2593 enforceConnectivityInternalPermission();
2594 return mTethering.getTetheredDhcpRanges();
2595 }
2596
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002597 // if ro.tether.denied = true we default to no tethering
2598 // gservices could set the secure setting to 1 though to enable it on a build where it
2599 // had previously been turned off.
2600 public boolean isTetheringSupported() {
2601 enforceTetherAccessPermission();
2602 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002603 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002604 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2605 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002606 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2607 mTethering.getTetherableWifiRegexs().length != 0 ||
2608 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2609 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002610 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002611
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002612 // Called when we lose the default network and have no replacement yet.
2613 // This will automatically be cleared after X seconds or a new default network
2614 // becomes CONNECTED, whichever happens first. The timer is started by the
2615 // first caller and not restarted by subsequent callers.
2616 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002617 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002618 synchronized (this) {
2619 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002620 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002621 mNetTransitionWakeLock.acquire();
2622 mNetTransitionWakeLockCausedBy = forWhom;
2623 }
2624 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002625 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002626 mNetTransitionWakeLockTimeout);
2627 return;
2628 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002629
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002630 // 100 percent is full good, 0 is full bad.
2631 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002632 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002633 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002634 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002635 }
2636
Paul Jensenbfd17b72015-04-07 12:43:13 -04002637 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002638 enforceAccessPermission();
2639 enforceInternetPermission();
2640
Paul Jensenbfd17b72015-04-07 12:43:13 -04002641 NetworkAgentInfo nai;
2642 if (network == null) {
2643 nai = getDefaultNetwork();
2644 } else {
2645 nai = getNetworkAgentInfoForNetwork(network);
2646 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002647 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002648 // Revalidate if the app report does not match our current validated state.
2649 if (hasConnectivity == nai.lastValidated) return;
2650 final int uid = Binder.getCallingUid();
2651 if (DBG) {
2652 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2653 ") by " + uid);
2654 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002655 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002656 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2657 // which isn't meant to work on uncreated networks.
2658 if (!nai.created) return;
2659
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002660 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002661
2662 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2663 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002664 }
2665
Paul Jensen25a217c2015-02-27 22:55:47 -05002666 public void captivePortalAppResponse(Network network, int response, String actionToken) {
2667 if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2668 enforceConnectivityInternalPermission();
2669 }
2670 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2671 if (nai == null) return;
2672 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2673 actionToken);
2674 }
2675
Paul Jensene0bef712014-12-10 15:12:18 -05002676 public ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002677 // this information is already available as a world read/writable jvm property
2678 // so this API change wouldn't have a benifit. It also breaks the passing
2679 // of proxy info to all the JVMs.
2680 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002681 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002682 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002683 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2684 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002685 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002686 }
2687
Paul Jensene0bef712014-12-10 15:12:18 -05002688 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2689 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2690 // proxy is null then there is no proxy in place).
2691 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2692 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2693 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2694 proxy = null;
2695 }
2696 return proxy;
2697 }
2698
2699 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2700 // better for determining if a new proxy broadcast is necessary:
2701 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2702 // avoid unnecessary broadcasts.
2703 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2704 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2705 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2706 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2707 // all set.
2708 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2709 a = canonicalizeProxyInfo(a);
2710 b = canonicalizeProxyInfo(b);
2711 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2712 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2713 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2714 }
2715
Jason Monk207900c2014-04-25 15:00:09 -04002716 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002717 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002718
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002719 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002720 if (proxyProperties == mGlobalProxy) return;
2721 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2722 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2723
2724 String host = "";
2725 int port = 0;
2726 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002727 String pacFileUrl = "";
2728 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002729 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002730 if (!proxyProperties.isValid()) {
2731 if (DBG)
2732 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2733 return;
2734 }
Jason Monk207900c2014-04-25 15:00:09 -04002735 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002736 host = mGlobalProxy.getHost();
2737 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002738 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002739 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002740 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002741 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002742 } else {
2743 mGlobalProxy = null;
2744 }
2745 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002746 final long token = Binder.clearCallingIdentity();
2747 try {
2748 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2749 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2750 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2751 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002752 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002753 } finally {
2754 Binder.restoreCallingIdentity(token);
2755 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002756
Jason Monkcf0f97a2014-10-02 15:39:38 -04002757 if (mGlobalProxy == null) {
2758 proxyProperties = mDefaultProxy;
2759 }
2760 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002761 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002762 }
2763
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002764 private void loadGlobalProxy() {
2765 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002766 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2767 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2768 String exclList = Settings.Global.getString(res,
2769 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002770 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2771 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002772 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002773 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002774 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002775 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002776 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002777 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002778 if (!proxyProperties.isValid()) {
2779 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2780 return;
2781 }
2782
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002783 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002784 mGlobalProxy = proxyProperties;
2785 }
2786 }
2787 }
2788
Jason Monk207900c2014-04-25 15:00:09 -04002789 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002790 // this information is already available as a world read/writable jvm property
2791 // so this API change wouldn't have a benifit. It also breaks the passing
2792 // of proxy info to all the JVMs.
2793 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002794 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002795 return mGlobalProxy;
2796 }
2797 }
2798
Jason Monk207900c2014-04-25 15:00:09 -04002799 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002800 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002801 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002802 proxy = null;
2803 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002804 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002805 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002806 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002807 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002808 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2809 return;
2810 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002811
2812 // This call could be coming from the PacManager, containing the port of the local
2813 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2814 // global (to get the correct local port), and send a broadcast.
2815 // TODO: Switch PacManager to have its own message to send back rather than
2816 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002817 if ((mGlobalProxy != null) && (proxy != null)
2818 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002819 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2820 mGlobalProxy = proxy;
2821 sendProxyBroadcast(mGlobalProxy);
2822 return;
2823 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002824 mDefaultProxy = proxy;
2825
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002826 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002827 if (!mDefaultProxyDisabled) {
2828 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002829 }
2830 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002831 }
2832
Paul Jensene0bef712014-12-10 15:12:18 -05002833 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2834 // This method gets called when any network changes proxy, but the broadcast only ever contains
2835 // the default proxy (even if it hasn't changed).
2836 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2837 // world where an app might be bound to a non-default network.
2838 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2839 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2840 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2841
2842 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2843 sendProxyBroadcast(getDefaultProxy());
2844 }
2845 }
2846
Robert Greenwalt434203a2010-10-11 16:00:27 -07002847 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002848 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2849 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002850 if (!TextUtils.isEmpty(proxy)) {
2851 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002852 if (data.length == 0) {
2853 return;
2854 }
2855
Robert Greenwalt434203a2010-10-11 16:00:27 -07002856 String proxyHost = data[0];
2857 int proxyPort = 8080;
2858 if (data.length > 1) {
2859 try {
2860 proxyPort = Integer.parseInt(data[1]);
2861 } catch (NumberFormatException e) {
2862 return;
2863 }
2864 }
Jason Monk207900c2014-04-25 15:00:09 -04002865 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002866 setGlobalProxy(p);
2867 }
2868 }
2869
Jason Monk207900c2014-04-25 15:00:09 -04002870 private void sendProxyBroadcast(ProxyInfo proxy) {
2871 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002872 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002873 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002874 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002875 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2876 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002877 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002878 final long ident = Binder.clearCallingIdentity();
2879 try {
2880 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2881 } finally {
2882 Binder.restoreCallingIdentity(ident);
2883 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002884 }
2885
2886 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002887 final private HashMap<Uri, Integer> mUriEventMap;
2888 final private Context mContext;
2889 final private Handler mHandler;
2890
2891 SettingsObserver(Context context, Handler handler) {
2892 super(null);
2893 mUriEventMap = new HashMap<Uri, Integer>();
2894 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002895 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002896 }
2897
Erik Klineda4bfa82015-04-30 12:58:40 +09002898 void observe(Uri uri, int what) {
2899 mUriEventMap.put(uri, what);
2900 final ContentResolver resolver = mContext.getContentResolver();
2901 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002902 }
2903
2904 @Override
2905 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002906 Slog.wtf(TAG, "Should never be reached.");
2907 }
2908
2909 @Override
2910 public void onChange(boolean selfChange, Uri uri) {
2911 final Integer what = mUriEventMap.get(uri);
2912 if (what != null) {
2913 mHandler.obtainMessage(what.intValue()).sendToTarget();
2914 } else {
2915 loge("No matching event to send for URI=" + uri);
2916 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002917 }
2918 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002919
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002920 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002921 Slog.d(TAG, s);
2922 }
2923
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002924 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002925 Slog.e(TAG, s);
2926 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002927
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002928 private static <T> T checkNotNull(T value, String message) {
2929 if (value == null) {
2930 throw new NullPointerException(message);
2931 }
2932 return value;
2933 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002934
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002935 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002936 * Prepare for a VPN application.
Jeff Davidson9a1da682014-11-11 13:52:58 -08002937 * Permissions are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002938 * @hide
2939 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002940 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002941 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002942 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002943 int user = UserHandle.getUserId(Binder.getCallingUid());
2944 synchronized(mVpns) {
2945 return mVpns.get(user).prepare(oldPackage, newPackage);
2946 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002947 }
2948
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002949 /**
Jeff Davidson05542602014-08-11 14:07:27 -07002950 * Set whether the current VPN package has the ability to launch VPNs without
Jeff Davidson9a1da682014-11-11 13:52:58 -08002951 * user intervention. This method is used by system-privileged apps.
2952 * Permissions are checked in Vpn class.
Jeff Davidson05542602014-08-11 14:07:27 -07002953 * @hide
2954 */
2955 @Override
2956 public void setVpnPackageAuthorization(boolean authorized) {
2957 int user = UserHandle.getUserId(Binder.getCallingUid());
2958 synchronized(mVpns) {
2959 mVpns.get(user).setPackageAuthorization(authorized);
2960 }
2961 }
2962
2963 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002964 * Configure a TUN interface and return its file descriptor. Parameters
2965 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002966 * and not available in ConnectivityManager. Permissions are checked in
2967 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002968 * @hide
2969 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002970 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002971 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002972 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002973 int user = UserHandle.getUserId(Binder.getCallingUid());
2974 synchronized(mVpns) {
2975 return mVpns.get(user).establish(config);
2976 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002977 }
2978
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002979 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07002980 * Start legacy VPN, controlling native daemons as needed. Creates a
2981 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002982 */
2983 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07002984 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002985 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07002986 final LinkProperties egress = getActiveLinkProperties();
2987 if (egress == null) {
2988 throw new IllegalStateException("Missing active network connection");
2989 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002990 int user = UserHandle.getUserId(Binder.getCallingUid());
2991 synchronized(mVpns) {
2992 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
2993 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002994 }
2995
2996 /**
2997 * Return the information of the ongoing legacy VPN. This method is used
2998 * by VpnSettings and not available in ConnectivityManager. Permissions
2999 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003000 */
3001 @Override
3002 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003003 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003004 int user = UserHandle.getUserId(Binder.getCallingUid());
3005 synchronized(mVpns) {
3006 return mVpns.get(user).getLegacyVpnInfo();
3007 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003008 }
3009
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003010 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003011 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3012 * and not available in ConnectivityManager.
3013 */
3014 @Override
3015 public VpnInfo[] getAllVpnInfo() {
3016 enforceConnectivityInternalPermission();
3017 if (mLockdownEnabled) {
3018 return new VpnInfo[0];
3019 }
3020
3021 synchronized(mVpns) {
3022 List<VpnInfo> infoList = new ArrayList<>();
3023 for (int i = 0; i < mVpns.size(); i++) {
3024 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3025 if (info != null) {
3026 infoList.add(info);
3027 }
3028 }
3029 return infoList.toArray(new VpnInfo[infoList.size()]);
3030 }
3031 }
3032
3033 /**
3034 * @return VPN information for accounting, or null if we can't retrieve all required
3035 * information, e.g primary underlying iface.
3036 */
3037 @Nullable
3038 private VpnInfo createVpnInfo(Vpn vpn) {
3039 VpnInfo info = vpn.getVpnInfo();
3040 if (info == null) {
3041 return null;
3042 }
3043 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3044 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3045 // the underlyingNetworks list.
3046 if (underlyingNetworks == null) {
3047 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3048 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3049 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3050 }
3051 } else if (underlyingNetworks.length > 0) {
3052 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3053 if (linkProperties != null) {
3054 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3055 }
3056 }
3057 return info.primaryUnderlyingIface == null ? null : info;
3058 }
3059
3060 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003061 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3062 * not available in ConnectivityManager.
3063 * Permissions are checked in Vpn class.
3064 * @hide
3065 */
3066 @Override
3067 public VpnConfig getVpnConfig() {
3068 int user = UserHandle.getUserId(Binder.getCallingUid());
3069 synchronized(mVpns) {
3070 return mVpns.get(user).getVpnConfig();
3071 }
3072 }
3073
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003074 @Override
3075 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003076 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3077 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3078 return false;
3079 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003080
3081 // Tear down existing lockdown if profile was removed
3082 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3083 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003084 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003085 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3086 return false;
3087 }
3088
3089 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3090 final VpnProfile profile = VpnProfile.decode(
3091 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003092 int user = UserHandle.getUserId(Binder.getCallingUid());
3093 synchronized(mVpns) {
3094 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3095 profile));
3096 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003097 } else {
3098 setLockdownTracker(null);
3099 }
3100
3101 return true;
3102 }
3103
3104 /**
3105 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3106 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3107 */
3108 private void setLockdownTracker(LockdownVpnTracker tracker) {
3109 // Shutdown any existing tracker
3110 final LockdownVpnTracker existing = mLockdownTracker;
3111 mLockdownTracker = null;
3112 if (existing != null) {
3113 existing.shutdown();
3114 }
3115
3116 try {
3117 if (tracker != null) {
3118 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003119 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003120 mLockdownTracker = tracker;
3121 mLockdownTracker.init();
3122 } else {
3123 mNetd.setFirewallEnabled(false);
3124 }
3125 } catch (RemoteException e) {
3126 // ignored; NMS lives inside system_server
3127 }
3128 }
3129
3130 private void throwIfLockdownEnabled() {
3131 if (mLockdownEnabled) {
3132 throw new IllegalStateException("Unavailable in lockdown mode");
3133 }
3134 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003135
Wink Savilleab9321d2013-06-29 21:10:57 -07003136 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003137 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003138 // TODO: Remove? Any reason to trigger a provisioning check?
3139 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003140 }
3141
3142 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3143 private volatile boolean mIsNotificationVisible = false;
3144
Paul Jensen89e0f092014-09-15 15:59:36 -04003145 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003146 if (DBG) {
3147 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003148 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003149 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003150 Intent intent = new Intent(action);
3151 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003152 // Concatenate the range of types onto the range of NetIDs.
3153 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Paul Jensen89e0f092014-09-15 15:59:36 -04003154 setProvNotificationVisibleIntent(visible, id, networkType, null, pendingIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003155 }
3156
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003157 /**
3158 * Show or hide network provisioning notificaitons.
3159 *
3160 * @param id an identifier that uniquely identifies this notification. This must match
3161 * between show and hide calls. We use the NetID value but for legacy callers
3162 * we concatenate the range of types with the range of NetIDs.
3163 */
3164 private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
Paul Jensen869868be2014-05-15 10:33:05 -04003165 String extraInfo, PendingIntent intent) {
3166 if (DBG) {
3167 log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
3168 networkType + " extraInfo=" + extraInfo);
3169 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003170
3171 Resources r = Resources.getSystem();
3172 NotificationManager notificationManager = (NotificationManager) mContext
3173 .getSystemService(Context.NOTIFICATION_SERVICE);
3174
3175 if (visible) {
3176 CharSequence title;
3177 CharSequence details;
3178 int icon;
Wink Saville948282b2013-08-29 08:55:16 -07003179 Notification notification = new Notification();
3180 switch (networkType) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003181 case ConnectivityManager.TYPE_WIFI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003182 title = r.getString(R.string.wifi_available_sign_in, 0);
3183 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003184 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003185 icon = R.drawable.stat_notify_wifi_in_range;
3186 break;
3187 case ConnectivityManager.TYPE_MOBILE:
3188 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003189 title = r.getString(R.string.network_available_sign_in, 0);
3190 // TODO: Change this to pull from NetworkInfo once a printable
3191 // name has been added to it
3192 details = mTelephonyManager.getNetworkOperatorName();
3193 icon = R.drawable.stat_notify_rssi_in_range;
3194 break;
3195 default:
Wink Savilleab9321d2013-06-29 21:10:57 -07003196 title = r.getString(R.string.network_available_sign_in, 0);
3197 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003198 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003199 icon = R.drawable.stat_notify_rssi_in_range;
3200 break;
3201 }
3202
Wink Savilleab9321d2013-06-29 21:10:57 -07003203 notification.when = 0;
3204 notification.icon = icon;
3205 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Savilleab9321d2013-06-29 21:10:57 -07003206 notification.tickerText = title;
Alan Viverette4a357cd2015-03-18 18:37:18 -07003207 notification.color = mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02003208 com.android.internal.R.color.system_notification_accent_color);
Wink Savilleab9321d2013-06-29 21:10:57 -07003209 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003210 notification.contentIntent = intent;
Wink Savilleab9321d2013-06-29 21:10:57 -07003211
Wink Saville948282b2013-08-29 08:55:16 -07003212 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003213 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003214 } catch (NullPointerException npe) {
3215 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
3216 npe.printStackTrace();
3217 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003218 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003219 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003220 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003221 } catch (NullPointerException npe) {
3222 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
3223 npe.printStackTrace();
3224 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003225 }
Wink Saville948282b2013-08-29 08:55:16 -07003226 mIsNotificationVisible = visible;
Wink Savilleab9321d2013-06-29 21:10:57 -07003227 }
3228
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003229 /** Location to an updatable file listing carrier provisioning urls.
3230 * An example:
3231 *
3232 * <?xml version="1.0" encoding="utf-8"?>
3233 * <provisioningUrls>
3234 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
3235 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
3236 * </provisioningUrls>
3237 */
3238 private static final String PROVISIONING_URL_PATH =
3239 "/data/misc/radio/provisioning_urls.xml";
3240 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003241
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003242 /** XML tag for root element. */
3243 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3244 /** XML tag for individual url */
3245 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3246 /** XML tag for redirected url */
3247 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
3248 /** XML attribute for mcc */
3249 private static final String ATTR_MCC = "mcc";
3250 /** XML attribute for mnc */
3251 private static final String ATTR_MNC = "mnc";
3252
3253 private static final int REDIRECTED_PROVISIONING = 1;
3254 private static final int PROVISIONING = 2;
3255
3256 private String getProvisioningUrlBaseFromFile(int type) {
3257 FileReader fileReader = null;
3258 XmlPullParser parser = null;
3259 Configuration config = mContext.getResources().getConfiguration();
3260 String tagType;
3261
3262 switch (type) {
3263 case PROVISIONING:
3264 tagType = TAG_PROVISIONING_URL;
3265 break;
3266 case REDIRECTED_PROVISIONING:
3267 tagType = TAG_REDIRECTED_URL;
3268 break;
3269 default:
3270 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3271 type);
3272 }
3273
3274 try {
3275 fileReader = new FileReader(mProvisioningUrlFile);
3276 parser = Xml.newPullParser();
3277 parser.setInput(fileReader);
3278 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3279
3280 while (true) {
3281 XmlUtils.nextElement(parser);
3282
3283 String element = parser.getName();
3284 if (element == null) break;
3285
3286 if (element.equals(tagType)) {
3287 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3288 try {
3289 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3290 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3291 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3292 parser.next();
3293 if (parser.getEventType() == XmlPullParser.TEXT) {
3294 return parser.getText();
3295 }
3296 }
3297 }
3298 } catch (NumberFormatException e) {
3299 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3300 }
3301 }
3302 }
3303 return null;
3304 } catch (FileNotFoundException e) {
3305 loge("Carrier Provisioning Urls file not found");
3306 } catch (XmlPullParserException e) {
3307 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3308 } catch (IOException e) {
3309 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3310 } finally {
3311 if (fileReader != null) {
3312 try {
3313 fileReader.close();
3314 } catch (IOException e) {}
3315 }
3316 }
3317 return null;
3318 }
3319
Wink Saville42d4f082013-07-20 20:31:59 -07003320 @Override
3321 public String getMobileRedirectedProvisioningUrl() {
3322 enforceConnectivityInternalPermission();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003323 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3324 if (TextUtils.isEmpty(url)) {
3325 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3326 }
3327 return url;
3328 }
3329
Wink Saville42d4f082013-07-20 20:31:59 -07003330 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003331 public String getMobileProvisioningUrl() {
3332 enforceConnectivityInternalPermission();
3333 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3334 if (TextUtils.isEmpty(url)) {
3335 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003336 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003337 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003338 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003339 }
Wink Saville8cf35602013-07-10 23:00:07 -07003340 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003341 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003342 String phoneNumber = mTelephonyManager.getLine1Number();
3343 if (TextUtils.isEmpty(phoneNumber)) {
3344 phoneNumber = "0000000000";
3345 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003346 url = String.format(url,
3347 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3348 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003349 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003350 }
3351
Wink Savilleab9321d2013-06-29 21:10:57 -07003352 return url;
3353 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003354
Wink Saville948282b2013-08-29 08:55:16 -07003355 @Override
3356 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003357 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003358 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003359 final long ident = Binder.clearCallingIdentity();
3360 try {
3361 setProvNotificationVisible(visible, networkType, action);
3362 } finally {
3363 Binder.restoreCallingIdentity(ident);
3364 }
Wink Saville948282b2013-08-29 08:55:16 -07003365 }
Wink Saville7788c612013-08-29 14:57:08 -07003366
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003367 @Override
3368 public void setAirplaneMode(boolean enable) {
3369 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003370 final long ident = Binder.clearCallingIdentity();
3371 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003372 final ContentResolver cr = mContext.getContentResolver();
3373 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3374 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3375 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003376 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003377 } finally {
3378 Binder.restoreCallingIdentity(ident);
3379 }
3380 }
3381
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003382 private void onUserStart(int userId) {
3383 synchronized(mVpns) {
3384 Vpn userVpn = mVpns.get(userId);
3385 if (userVpn != null) {
3386 loge("Starting user already has a VPN");
3387 return;
3388 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003389 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003390 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003391 }
3392 }
3393
3394 private void onUserStop(int userId) {
3395 synchronized(mVpns) {
3396 Vpn userVpn = mVpns.get(userId);
3397 if (userVpn == null) {
3398 loge("Stopping user has no VPN");
3399 return;
3400 }
3401 mVpns.delete(userId);
3402 }
3403 }
3404
3405 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3406 @Override
3407 public void onReceive(Context context, Intent intent) {
3408 final String action = intent.getAction();
3409 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3410 if (userId == UserHandle.USER_NULL) return;
3411
3412 if (Intent.ACTION_USER_STARTING.equals(action)) {
3413 onUserStart(userId);
3414 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3415 onUserStop(userId);
3416 }
3417 }
3418 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003419
Robert Greenwalta67be032014-05-16 15:49:14 -07003420 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3421 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003422 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3423 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003424
Robert Greenwalta67be032014-05-16 15:49:14 -07003425 private static class NetworkFactoryInfo {
3426 public final String name;
3427 public final Messenger messenger;
3428 public final AsyncChannel asyncChannel;
3429
3430 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3431 this.name = name;
3432 this.messenger = messenger;
3433 this.asyncChannel = asyncChannel;
3434 }
3435 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003436
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003437 /**
3438 * Tracks info about the requester.
3439 * Also used to notice when the calling process dies so we can self-expire
3440 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003441 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3442 static final boolean REQUEST = true;
3443 static final boolean LISTEN = false;
3444
3445 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003446 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003447 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003448 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003449 final int mPid;
3450 final int mUid;
3451 final Messenger messenger;
3452 final boolean isRequest;
3453
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003454 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3455 request = r;
3456 mPendingIntent = pi;
3457 messenger = null;
3458 mBinder = null;
3459 mPid = getCallingPid();
3460 mUid = getCallingUid();
3461 this.isRequest = isRequest;
3462 }
3463
Robert Greenwalt9258c642014-03-26 16:47:06 -07003464 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3465 super();
3466 messenger = m;
3467 request = r;
3468 mBinder = binder;
3469 mPid = getCallingPid();
3470 mUid = getCallingUid();
3471 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003472 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003473
3474 try {
3475 mBinder.linkToDeath(this, 0);
3476 } catch (RemoteException e) {
3477 binderDied();
3478 }
3479 }
3480
3481 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003482 if (mBinder != null) {
3483 mBinder.unlinkToDeath(this, 0);
3484 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003485 }
3486
3487 public void binderDied() {
3488 log("ConnectivityService NetworkRequestInfo binderDied(" +
3489 request + ", " + mBinder + ")");
3490 releaseNetworkRequest(request);
3491 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003492
3493 public String toString() {
3494 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003495 mPid + " for " + request +
3496 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003497 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003498 }
3499
3500 @Override
3501 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003502 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003503 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003504 enforceNetworkRequestPermissions(networkCapabilities);
3505 enforceMeteredApnPolicy(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003506
Robert Greenwalt6078b502014-06-11 16:05:07 -07003507 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003508 throw new IllegalArgumentException("Bad timeout specified");
3509 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003510
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003511 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3512 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003513 if (DBG) log("requestNetwork for " + networkRequest);
3514 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3515 NetworkRequestInfo.REQUEST);
3516
3517 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003518 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003519 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003520 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003521 }
3522 return networkRequest;
3523 }
3524
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003525 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
3526 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
3527 == false) {
3528 enforceConnectivityInternalPermission();
3529 } else {
3530 enforceChangePermission();
3531 }
3532 }
3533
fenglub15e72b2015-03-20 11:29:56 -07003534 @Override
fengludb571472015-04-21 17:12:05 -07003535 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003536 enforceAccessPermission();
3537 NetworkAgentInfo nai = null;
3538 if (network == null) {
3539 return false;
3540 }
3541 synchronized (mNetworkForNetId) {
3542 nai = mNetworkForNetId.get(network.netId);
3543 }
3544 if (nai != null) {
3545 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3546 return true;
3547 }
3548 return false;
3549 }
3550
3551
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003552 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3553 // if UID is restricted, don't allow them to bring up metered APNs
3554 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
3555 == false) {
3556 final int uidRules;
3557 final int uid = Binder.getCallingUid();
3558 synchronized(mRulesLock) {
3559 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3560 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003561 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003562 // we could silently fail or we can filter the available nets to only give
3563 // them those they have access to. Chose the more useful
3564 networkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3565 }
3566 }
3567 }
3568
Robert Greenwalt9258c642014-03-26 16:47:06 -07003569 @Override
3570 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3571 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003572 checkNotNull(operation, "PendingIntent cannot be null.");
3573 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3574 enforceNetworkRequestPermissions(networkCapabilities);
3575 enforceMeteredApnPolicy(networkCapabilities);
3576
3577 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3578 nextNetworkRequestId());
3579 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3580 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3581 NetworkRequestInfo.REQUEST);
3582 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3583 nri));
3584 return networkRequest;
3585 }
3586
Jeremy Joslin79294842014-12-03 17:15:28 -08003587 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3588 mHandler.sendMessageDelayed(
3589 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3590 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3591 }
3592
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003593 @Override
3594 public void releasePendingNetworkRequest(PendingIntent operation) {
3595 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3596 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003597 }
3598
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003599 // In order to implement the compatibility measure for pre-M apps that call
3600 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3601 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3602 // This ensures it has permission to do so.
3603 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3604 if (nc == null) {
3605 return false;
3606 }
3607 int[] transportTypes = nc.getTransportTypes();
3608 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3609 return false;
3610 }
3611 try {
3612 mContext.enforceCallingOrSelfPermission(
3613 android.Manifest.permission.ACCESS_WIFI_STATE,
3614 "ConnectivityService");
3615 } catch (SecurityException e) {
3616 return false;
3617 }
3618 return true;
3619 }
3620
Robert Greenwalt9258c642014-03-26 16:47:06 -07003621 @Override
3622 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3623 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003624 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3625 enforceAccessPermission();
3626 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003627
3628 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003629 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003630 if (DBG) log("listenForNetwork for " + networkRequest);
3631 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3632 NetworkRequestInfo.LISTEN);
3633
3634 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3635 return networkRequest;
3636 }
3637
3638 @Override
3639 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3640 PendingIntent operation) {
3641 }
3642
3643 @Override
3644 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003645 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3646 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003647 }
3648
3649 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003650 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003651 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003652 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3653 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003654 }
3655
Robert Greenwalta67be032014-05-16 15:49:14 -07003656 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003657 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003658 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3659 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3660 }
3661
3662 @Override
3663 public void unregisterNetworkFactory(Messenger messenger) {
3664 enforceConnectivityInternalPermission();
3665 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3666 }
3667
3668 private void handleUnregisterNetworkFactory(Messenger messenger) {
3669 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3670 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003671 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003672 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003673 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003674 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003675 }
3676
Robert Greenwalt7b816022014-04-18 15:25:25 -07003677 /**
3678 * NetworkAgentInfo supporting a request by requestId.
3679 * These have already been vetted (their Capabilities satisfy the request)
3680 * and the are the highest scored network available.
3681 * the are keyed off the Requests requestId.
3682 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003683 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003684 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3685 new SparseArray<NetworkAgentInfo>();
3686
Paul Jensen31a94f42015-02-13 14:18:39 -05003687 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3688 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003689 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3690 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003691 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3692 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3693 // there may not be a strict 1:1 correlation between the two.
3694 @GuardedBy("mNetworkForNetId")
3695 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003696
Robert Greenwalt7b816022014-04-18 15:25:25 -07003697 // NetworkAgentInfo keyed off its connecting messenger
3698 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003699 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003700 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3701 new HashMap<Messenger, NetworkAgentInfo>();
3702
Paul Jensen2c311d62014-11-17 12:34:51 -05003703 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003704 private final NetworkRequest mDefaultRequest;
3705
Erik Klineda4bfa82015-04-30 12:58:40 +09003706 // Request used to optionally keep mobile data active even when higher
3707 // priority networks like Wi-Fi are active.
3708 private final NetworkRequest mDefaultMobileDataRequest;
3709
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003710 private NetworkAgentInfo getDefaultNetwork() {
3711 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3712 }
3713
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003714 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003715 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003716 }
3717
Paul Jensen31a94f42015-02-13 14:18:39 -05003718 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003719 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003720 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003721 enforceConnectivityInternalPermission();
3722
Paul Jensen2c311d62014-11-17 12:34:51 -05003723 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3724 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003725 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003726 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3727 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3728 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003729 synchronized (this) {
3730 nai.networkMonitor.systemReady = mSystemReady;
3731 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003732 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003733 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003734 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003735 }
3736
3737 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3738 if (VDBG) log("Got NetworkAgent Messenger");
3739 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003740 synchronized (mNetworkForNetId) {
3741 mNetworkForNetId.put(na.network.netId, na);
3742 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003743 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3744 NetworkInfo networkInfo = na.networkInfo;
3745 na.networkInfo = null;
3746 updateNetworkInfo(na, networkInfo);
3747 }
3748
3749 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3750 LinkProperties newLp = networkAgent.linkProperties;
3751 int netId = networkAgent.network.netId;
3752
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003753 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3754 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003755 if (networkAgent.clatd != null) {
3756 networkAgent.clatd.fixupLinkProperties(oldLp);
3757 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003758
Paul Jensen992f2522014-04-28 10:33:11 -04003759 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003760 updateMtu(newLp, oldLp);
3761 // TODO - figure out what to do for clat
3762// for (LinkProperties lp : newLp.getStackedLinks()) {
3763// updateMtu(lp, null);
3764// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003765 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003766
3767 // TODO: deprecate and remove mDefaultDns when we can do so safely.
3768 // For now, use it only when the network has Internet access. http://b/18327075
3769 final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3770 NetworkCapabilities.NET_CAPABILITY_INTERNET);
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003771 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003772 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3773
Paul Jensen3b759822014-05-13 11:44:01 -04003774 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003775 if (isDefaultNetwork(networkAgent)) {
3776 handleApplyDefaultProxy(newLp.getHttpProxy());
3777 } else {
3778 updateProxy(newLp, oldLp, networkAgent);
3779 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003780 // TODO - move this check to cover the whole function
3781 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003782 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003783 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3784 }
Paul Jensen3b759822014-05-13 11:44:01 -04003785 }
3786
Lorenzo Colitti95439462014-10-09 13:44:48 +09003787 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3788 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3789 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003790
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003791 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003792 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3793 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003794 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003795 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003796 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003797 }
Paul Jensen992f2522014-04-28 10:33:11 -04003798
3799 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3800 CompareResult<String> interfaceDiff = new CompareResult<String>();
3801 if (oldLp != null) {
3802 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3803 } else if (newLp != null) {
3804 interfaceDiff.added = newLp.getAllInterfaceNames();
3805 }
3806 for (String iface : interfaceDiff.added) {
3807 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003808 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003809 mNetd.addInterfaceToNetwork(iface, netId);
3810 } catch (Exception e) {
3811 loge("Exception adding interface: " + e);
3812 }
3813 }
3814 for (String iface : interfaceDiff.removed) {
3815 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003816 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003817 mNetd.removeInterfaceFromNetwork(iface, netId);
3818 } catch (Exception e) {
3819 loge("Exception removing interface: " + e);
3820 }
3821 }
3822 }
3823
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003824 /**
3825 * Have netd update routes from oldLp to newLp.
3826 * @return true if routes changed between oldLp and newLp
3827 */
3828 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003829 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3830 if (oldLp != null) {
3831 routeDiff = oldLp.compareAllRoutes(newLp);
3832 } else if (newLp != null) {
3833 routeDiff.added = newLp.getAllRoutes();
3834 }
3835
3836 // add routes before removing old in case it helps with continuous connectivity
3837
3838 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3839 for (RouteInfo route : routeDiff.added) {
3840 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003841 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003842 try {
3843 mNetd.addRoute(netId, route);
3844 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003845 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3846 loge("Exception in addRoute for non-gateway: " + e);
3847 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003848 }
3849 }
3850 for (RouteInfo route : routeDiff.added) {
3851 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003852 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003853 try {
3854 mNetd.addRoute(netId, route);
3855 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003856 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3857 loge("Exception in addRoute for gateway: " + e);
3858 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003859 }
3860 }
3861
3862 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003863 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003864 try {
3865 mNetd.removeRoute(netId, route);
3866 } catch (Exception e) {
3867 loge("Exception in removeRoute: " + e);
3868 }
3869 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003870 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003871 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003872 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3873 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003874 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Robert Greenwaltdf2b8782014-06-06 10:30:11 -07003875 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003876 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003877 dnses = new ArrayList();
3878 dnses.add(mDefaultDns);
3879 if (DBG) {
3880 loge("no dns provided for netId " + netId + ", so using defaults");
3881 }
3882 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003883 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003884 try {
3885 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3886 newLp.getDomains());
3887 } catch (Exception e) {
3888 loge("Exception in setDnsServersForNetwork: " + e);
3889 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003890 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3891 if (defaultNai != null && defaultNai.network.netId == netId) {
3892 setDefaultDnsSystemProperties(dnses);
3893 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003894 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003895 } else if (flush) {
3896 try {
3897 mNetd.flushNetworkDnsCache(netId);
3898 } catch (Exception e) {
3899 loge("Exception in flushNetworkDnsCache: " + e);
3900 }
3901 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003902 }
3903 }
3904
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003905 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3906 int last = 0;
3907 for (InetAddress dns : dnses) {
3908 ++last;
3909 String key = "net.dns" + last;
3910 String value = dns.getHostAddress();
3911 SystemProperties.set(key, value);
3912 }
3913 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3914 String key = "net.dns" + i;
3915 SystemProperties.set(key, "");
3916 }
3917 mNumDnsEntries = last;
3918 }
3919
Robert Greenwalt7b816022014-04-18 15:25:25 -07003920 private void updateCapabilities(NetworkAgentInfo networkAgent,
3921 NetworkCapabilities networkCapabilities) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003922 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
3923 synchronized (networkAgent) {
3924 networkAgent.networkCapabilities = networkCapabilities;
3925 }
Jeff Davidson9634abe2014-11-04 16:48:27 -08003926 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003927 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07003928 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003929 }
3930
Paul Jensenc8b9a742014-09-30 15:37:41 -04003931 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
3932 for (int i = 0; i < nai.networkRequests.size(); i++) {
3933 NetworkRequest nr = nai.networkRequests.valueAt(i);
3934 // Don't send listening requests to factories. b/17393458
3935 if (!isRequest(nr)) continue;
3936 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
3937 }
3938 }
3939
Robert Greenwalt7b816022014-04-18 15:25:25 -07003940 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
3941 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07003942 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07003943 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
3944 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003945 }
3946 }
3947
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003948 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
3949 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08003950 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003951 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08003952 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
3953 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08003954 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003955 sendIntent(nri.mPendingIntent, intent);
3956 }
3957 // else not handled
3958 }
3959
3960 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
3961 mPendingIntentWakeLock.acquire();
3962 try {
3963 if (DBG) log("Sending " + pendingIntent);
3964 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
3965 } catch (PendingIntent.CanceledException e) {
3966 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
3967 mPendingIntentWakeLock.release();
3968 releasePendingNetworkRequest(pendingIntent);
3969 }
3970 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
3971 }
3972
3973 @Override
3974 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
3975 String resultData, Bundle resultExtras) {
3976 if (DBG) log("Finished sending " + pendingIntent);
3977 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08003978 // Release with a delay so the receiving client has an opportunity to put in its
3979 // own request.
3980 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003981 }
3982
Robert Greenwalt9258c642014-03-26 16:47:06 -07003983 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003984 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003985 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003986 Bundle bundle = new Bundle();
3987 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
3988 new NetworkRequest(nri.request));
3989 Message msg = Message.obtain();
3990 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
3991 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
3992 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
3993 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003994 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003995 case ConnectivityManager.CALLBACK_LOSING: {
3996 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
3997 break;
3998 }
3999 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4000 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4001 new NetworkCapabilities(networkAgent.networkCapabilities));
4002 break;
4003 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004004 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004005 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4006 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004007 break;
4008 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004009 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004010 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004011 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004012 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004013 if (VDBG) {
4014 log("sending notification " + notifyTypeToName(notificationType) +
4015 " for " + nri.request);
4016 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004017 nri.messenger.send(msg);
4018 } catch (RemoteException e) {
4019 // may occur naturally in the race of binder death.
4020 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4021 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004022 }
4023
Paul Jensenc8b9a742014-09-30 15:37:41 -04004024 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4025 for (int i = 0; i < nai.networkRequests.size(); i++) {
4026 NetworkRequest nr = nai.networkRequests.valueAt(i);
4027 // Ignore listening requests.
4028 if (!isRequest(nr)) continue;
4029 loge("Dead network still had at least " + nr);
4030 break;
4031 }
4032 nai.asyncChannel.disconnect();
4033 }
4034
Robert Greenwalt7b816022014-04-18 15:25:25 -07004035 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4036 if (oldNetwork == null) {
4037 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4038 return;
4039 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004040 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4041 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004042 }
4043
Paul Jensen27b02b72014-07-14 12:03:33 -04004044 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004045 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004046 setupDataActivityTracking(newNetwork);
4047 try {
4048 mNetd.setDefaultNetId(newNetwork.network.netId);
4049 } catch (Exception e) {
4050 loge("Exception setting default network :" + e);
4051 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004052 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004053 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004054 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004055 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004056 }
4057
Paul Jensen2161a8e2014-09-11 11:00:39 -04004058 // Handles a network appearing or improving its score.
4059 //
4060 // - Evaluates all current NetworkRequests that can be
4061 // satisfied by newNetwork, and reassigns to newNetwork
4062 // any such requests for which newNetwork is the best.
4063 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004064 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004065 // needed. A network is needed if it is the best network for
4066 // one or more NetworkRequests, or if it is a VPN.
4067 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004068 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05004069 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4070 //
4071 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4072 // networks that have no chance (i.e. even if validated)
4073 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004074 //
4075 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4076 // it does not remove NetworkRequests that other Networks could better satisfy.
4077 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4078 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4079 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004080 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004081 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004082 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05004083 // torn down if unneeded.
4084 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4085 // performed to tear down unvalidated networks that have no chance (i.e. even if
4086 // validated) of becoming the highest scoring network.
4087 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4088 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004089 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004090 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004091 loge("ERROR: nascent network not validated.");
4092 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004093 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004094 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004095 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004096 if (DBG) log("rematching " + newNetwork.name());
4097 // Find and migrate to this Network any NetworkRequests for
4098 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004099 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004100 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004101 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004102 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4103 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004104 if (DBG) {
4105 log("Network " + newNetwork.name() + " was already satisfying" +
4106 " request " + nri.request.requestId + ". No change.");
4107 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004108 keep = true;
4109 continue;
4110 }
4111
4112 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004113 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004114 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004115 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004116 // This is not a request, it's a callback listener.
4117 // Add it to newNetwork regardless of score.
Paul Jensen0311b2b2014-08-19 10:31:40 -04004118 newNetwork.addRequest(nri.request);
4119 continue;
4120 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004121
Robert Greenwalt7b816022014-04-18 15:25:25 -07004122 // next check if it's better than any current network we're using for
4123 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004124 if (VDBG) {
4125 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004126 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4127 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004128 }
4129 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004130 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004131 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004132 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004133 currentNetwork.networkRequests.remove(nri.request.requestId);
4134 currentNetwork.networkLingered.add(nri.request);
4135 affectedNetworks.add(currentNetwork);
4136 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004137 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004138 }
Paul Jensen573a0352015-01-08 10:49:34 -05004139 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004140 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07004141 newNetwork.addRequest(nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004142 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004143 // Tell NetworkFactories about the new score, so they can stop
4144 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004145 // TODO - this could get expensive if we have alot of requests for this
4146 // network. Think about if there is a way to reduce this. Push
4147 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004148 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004149 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004150 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004151 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004152 }
4153 }
4154 }
4155 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004156 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004157 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004158 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004159 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4160 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4161 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004162 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004163 }
4164 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004165 if (keep) {
4166 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004167 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004168 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004169 synchronized (ConnectivityService.this) {
4170 // have a new default network, release the transition wakelock in
4171 // a second if it's held. The second pause is to allow apps
4172 // to reconnect over the new network
4173 if (mNetTransitionWakeLock.isHeld()) {
4174 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4175 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4176 mNetTransitionWakeLockSerialNumber, 0),
4177 1000);
4178 }
4179 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004180 }
4181
4182 // do this after the default net is switched, but
4183 // before LegacyTypeTracker sends legacy broadcasts
4184 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4185
4186 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004187 // Maintain the illusion: since the legacy API only
4188 // understands one network at a time, we must pretend
4189 // that the current default network disconnected before
4190 // the new one connected.
4191 if (oldDefaultNetwork != null) {
4192 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4193 oldDefaultNetwork);
4194 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004195 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004196 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4197 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004198 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004199
4200 // Notify battery stats service about this network, both the normal
4201 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004202 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004203 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004204 final IBatteryStats bs = BatteryStatsService.getService();
4205 final int type = newNetwork.networkInfo.getType();
4206
4207 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4208 bs.noteNetworkInterfaceType(baseIface, type);
4209 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4210 final String stackedIface = stacked.getInterfaceName();
4211 bs.noteNetworkInterfaceType(stackedIface, type);
4212 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4213 }
4214 } catch (RemoteException ignored) {
4215 }
4216
Robert Greenwalt152ed372014-12-17 17:19:53 -08004217 // This has to happen after the notifyNetworkCallbacks as that tickles each
4218 // ConnectivityManager instance so that legacy requests correctly bind dns
4219 // requests to this network. The legacy users are listening for this bcast
4220 // and will generally do a dns request so they can ensureRouteToHost and if
4221 // they do that before the callbacks happen they'll use the default network.
4222 //
4223 // TODO: Is there still a race here? We send the broadcast
4224 // after sending the callback, but if the app can receive the
4225 // broadcast before the callback, it might still break.
4226 //
4227 // This *does* introduce a race where if the user uses the new api
4228 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4229 // they may get old info. Reverse this after the old startUsing api is removed.
4230 // This is on top of the multiple intent sequencing referenced in the todo above.
4231 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4232 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4233 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4234 // legacy type tracker filters out repeat adds
4235 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4236 }
4237 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004238
4239 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4240 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4241 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4242 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4243 if (newNetwork.isVPN()) {
4244 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4245 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004246 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004247 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05004248 // validated (and get evaluated against peers, one losing here), or get reaped (see
4249 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4250 // network. Networks that have been up for a while and are validated should be torn
4251 // down via the lingering process so communication on that network is given time to
4252 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004253 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04004254 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004255 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004256 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4257 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05004258 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004259 if (DBG) log("Reaping " + nai.name());
4260 teardownUnneededNetwork(nai);
4261 }
4262 }
4263 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004264 }
4265
Paul Jensen2161a8e2014-09-11 11:00:39 -04004266 // Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4267 // being disconnected.
4268 // If only one Network's score or capabilities have been modified since the last time
4269 // this function was called, pass this Network in via the "changed" arugment, otherwise
4270 // pass null.
4271 // If only one Network has been changed but its NetworkCapabilities have not changed,
4272 // pass in the Network's score (from getCurrentScore()) prior to the change via
4273 // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
4274 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4275 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4276 // to avoid the slowness. It is not simply enough to process just "changed", for
4277 // example in the case where "changed"'s score decreases and another network should begin
4278 // satifying a NetworkRequest that "changed" currently satisfies.
4279
4280 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4281 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4282 // rematchNetworkAndRequests() handles.
4283 if (changed != null && oldScore < changed.getCurrentScore()) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004284 rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
4285 ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004286 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004287 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4288 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4289 NascentState.NOT_JUST_VALIDATED,
4290 // Only reap the last time through the loop. Reaping before all rematching
4291 // is complete could incorrectly teardown a network that hasn't yet been
4292 // rematched.
4293 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4294 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004295 }
4296 }
4297 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004298
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004299 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004300 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004301 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004302 // For now only update icons for default connection.
4303 // TODO: Update WiFi and cellular icons separately. b/17237507
4304 if (!isDefaultNetwork(nai)) return;
4305
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004306 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004307 // Don't repeat publish.
4308 if (newInetCondition == mDefaultInetConditionPublished) return;
4309
4310 mDefaultInetConditionPublished = newInetCondition;
4311 sendInetConditionBroadcast(nai.networkInfo);
4312 }
4313
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004314 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4315 if (mLockdownTracker != null) {
4316 if (nai != null && nai.isVPN()) {
4317 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4318 } else {
4319 mLockdownTracker.onNetworkInfoChanged();
4320 }
4321 }
4322 }
4323
Robert Greenwalt7b816022014-04-18 15:25:25 -07004324 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4325 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004326 NetworkInfo oldInfo = null;
4327 synchronized (networkAgent) {
4328 oldInfo = networkAgent.networkInfo;
4329 networkAgent.networkInfo = newInfo;
4330 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004331 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004332
4333 if (oldInfo != null && oldInfo.getState() == state) {
4334 if (VDBG) log("ignoring duplicate network state non-change");
4335 return;
4336 }
4337 if (DBG) {
4338 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4339 (oldInfo == null ? "null" : oldInfo.getState()) +
4340 " to " + state);
4341 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004342
Paul Jenseneec75412014-08-04 12:21:19 -04004343 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004344 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004345 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004346 if (networkAgent.isVPN()) {
4347 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004348 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4349 (networkAgent.networkMisc == null ||
4350 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004351 } else {
4352 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4353 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004354 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004355 loge("Error creating network " + networkAgent.network.netId + ": "
4356 + e.getMessage());
4357 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004358 }
Paul Jenseneec75412014-08-04 12:21:19 -04004359 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004360 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004361 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004362
Paul Jensenca8f16a2014-05-09 12:47:55 -04004363 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004364 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004365
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004366 if (networkAgent.isVPN()) {
4367 // Temporarily disable the default proxy (not global).
4368 synchronized (mProxyLock) {
4369 if (!mDefaultProxyDisabled) {
4370 mDefaultProxyDisabled = true;
4371 if (mGlobalProxy == null && mDefaultProxy != null) {
4372 sendProxyBroadcast(null);
4373 }
4374 }
4375 }
4376 // TODO: support proxy per network.
4377 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004378
Paul Jensen2161a8e2014-09-11 11:00:39 -04004379 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004380 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4381 ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004382
4383 // This has to happen after matching the requests, because callbacks are just requests.
4384 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004385 } else if (state == NetworkInfo.State.DISCONNECTED ||
4386 state == NetworkInfo.State.SUSPENDED) {
4387 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004388 if (networkAgent.isVPN()) {
4389 synchronized (mProxyLock) {
4390 if (mDefaultProxyDisabled) {
4391 mDefaultProxyDisabled = false;
4392 if (mGlobalProxy == null && mDefaultProxy != null) {
4393 sendProxyBroadcast(mDefaultProxy);
4394 }
4395 }
4396 }
4397 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004398 }
4399 }
4400
Robert Greenwaltac96c522014-06-03 16:43:57 -07004401 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4402 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004403 if (score < 0) {
4404 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4405 "). Bumping score to min of 0");
4406 score = 0;
4407 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004408
Paul Jensen2161a8e2014-09-11 11:00:39 -04004409 final int oldScore = nai.getCurrentScore();
4410 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004411
Paul Jensen57a767f2014-11-19 13:01:46 -05004412 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004413
Paul Jensenc8b9a742014-09-30 15:37:41 -04004414 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004415 }
4416
Robert Greenwalt9258c642014-03-26 16:47:06 -07004417 // notify only this one new request of the current state
4418 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4419 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4420 // TODO - read state from monitor to decide what to send.
4421// if (nai.networkMonitor.isLingering()) {
4422// notifyType = NetworkCallbacks.LOSING;
4423// } else if (nai.networkMonitor.isEvaluating()) {
4424// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4425// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004426 if (nri.mPendingIntent == null) {
4427 callCallbackForRequest(nri, nai, notifyType);
4428 } else {
4429 sendPendingIntentForRequest(nri, nai, notifyType);
4430 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004431 }
4432
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004433 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004434 // The NetworkInfo we actually send out has no bearing on the real
4435 // state of affairs. For example, if the default connection is mobile,
4436 // and a request for HIPRI has just gone away, we need to pretend that
4437 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4438 // the state to DISCONNECTED, even though the network is of type MOBILE
4439 // and is still connected.
4440 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4441 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004442 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004443 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004444 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004445 } else {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004446 info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004447 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4448 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4449 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4450 if (info.isFailover()) {
4451 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4452 nai.networkInfo.setFailover(false);
4453 }
4454 if (info.getReason() != null) {
4455 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4456 }
4457 if (info.getExtraInfo() != null) {
4458 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4459 }
4460 NetworkAgentInfo newDefaultAgent = null;
4461 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4462 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4463 if (newDefaultAgent != null) {
4464 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4465 newDefaultAgent.networkInfo);
4466 } else {
4467 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4468 }
4469 }
4470 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4471 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004472 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004473 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004474 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004475 }
4476 }
4477 }
4478
Robert Greenwalt7b816022014-04-18 15:25:25 -07004479 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004480 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004481 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004482 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4483 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4484 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004485 if (nri.mPendingIntent == null) {
4486 callCallbackForRequest(nri, networkAgent, notifyType);
4487 } else {
4488 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4489 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004490 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004491 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004492
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004493 private String notifyTypeToName(int notifyType) {
4494 switch (notifyType) {
4495 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4496 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4497 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4498 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4499 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4500 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4501 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4502 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4503 }
4504 return "UNKNOWN";
4505 }
4506
Jeff Sharkey69736342014-12-08 14:50:12 -08004507 /**
4508 * Notify other system services that set of active ifaces has changed.
4509 */
4510 private void notifyIfacesChanged() {
4511 try {
4512 mStatsService.forceUpdateIfaces();
4513 } catch (Exception ignored) {
4514 }
4515 }
4516
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004517 @Override
4518 public boolean addVpnAddress(String address, int prefixLength) {
4519 throwIfLockdownEnabled();
4520 int user = UserHandle.getUserId(Binder.getCallingUid());
4521 synchronized (mVpns) {
4522 return mVpns.get(user).addAddress(address, prefixLength);
4523 }
4524 }
4525
4526 @Override
4527 public boolean removeVpnAddress(String address, int prefixLength) {
4528 throwIfLockdownEnabled();
4529 int user = UserHandle.getUserId(Binder.getCallingUid());
4530 synchronized (mVpns) {
4531 return mVpns.get(user).removeAddress(address, prefixLength);
4532 }
4533 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004534
4535 @Override
4536 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4537 throwIfLockdownEnabled();
4538 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004539 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004540 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004541 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004542 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004543 if (success) {
4544 notifyIfacesChanged();
4545 }
4546 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004547 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004548
4549 @Override
4550 public void factoryReset() {
4551 enforceConnectivityInternalPermission();
4552 // Turn airplane mode off
4553 setAirplaneMode(false);
4554
4555 // Untether
4556 for (String tether : getTetheredIfaces()) {
4557 untether(tether);
4558 }
4559
4560 // Turn VPN off
4561 VpnConfig vpnConfig = getVpnConfig();
4562 if (vpnConfig != null) {
4563 if (vpnConfig.legacy) {
4564 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN);
4565 } else {
4566 // Prevent this app from initiating VPN connections in the future without
4567 // user intervention.
4568 setVpnPackageAuthorization(false);
4569
4570 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN);
4571 }
4572 }
4573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004574}