blob: b06936129b75ff4852c70c2531320ed5ac99b146 [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;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070031import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070033import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070034
Wenchao Tongf5ea3402015-03-04 13:26:38 -080035import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080036import android.app.BroadcastOptions;
Wink Savilleab9321d2013-06-29 21:10:57 -070037import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070040import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.ContentResolver;
42import android.content.Context;
43import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070046import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090047import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090050import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070052import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070053import android.net.INetworkPolicyListener;
54import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070055import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080056import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070057import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070058import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070059import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070060import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070061import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070063import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070064import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070065import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070066import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070067import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070068import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070069import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040070import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070071import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040072import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040073import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090074import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090075import android.net.metrics.NetworkEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080077import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070078import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040079import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070081import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070082import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070083import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.Looper;
85import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070086import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070087import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070088import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070089import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070090import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080091import android.os.ResultReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070093import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040094import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070096import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070097import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070098import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070099import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700100import android.util.LocalLog;
101import android.util.LocalLog.ReadOnlyLocalLog;
102import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800103import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700104import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500105import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700106import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700107import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108
Wink Savilleab9321d2013-06-29 21:10:57 -0700109import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400110import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400111import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700112import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700113import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700114import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700115import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800116import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700117import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700118import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700119import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900120import com.android.internal.util.MessageUtils;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700121import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700122import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400123import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900124import com.android.server.connectivity.KeepaliveTracker;
Erik Kline379747a2015-06-05 17:47:34 +0900125import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900126import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700127import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400128import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400129import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700130import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800131import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700132import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700133import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700134import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700135import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700136import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700137
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700138import org.xmlpull.v1.XmlPullParser;
139import org.xmlpull.v1.XmlPullParserException;
140
141import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700143import java.io.FileNotFoundException;
144import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700145import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700147import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700148import java.net.InetAddress;
149import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700150import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700151import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700152import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700153import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700154import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700155import java.util.HashSet;
Lorenzo Colittic3f21f32015-07-06 23:50:27 +0900156import java.util.SortedSet;
157import java.util.TreeSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700158import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700159import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700160import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
162/**
163 * @hide
164 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800165public class ConnectivityService extends IConnectivityManager.Stub
166 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700167 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900169 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700170 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171
Jake Hamby786e71a2014-02-06 14:43:50 -0800172 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900173 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700174
Jeff Sharkey899223b2012-08-04 15:24:58 -0700175 // TODO: create better separation between radio types and network types
176
Robert Greenwalt42acef32009-08-12 16:08:25 -0700177 // how long to wait before switching back to a radio's default network
178 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
179 // system property that can override the above value
180 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
181 "android.telephony.apn-restore";
182
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900183 // How long to wait before putting up a "This network doesn't have an Internet connection,
184 // connect anyway?" dialog after the user selects a network that doesn't validate.
185 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
186
Jeremy Joslin79294842014-12-03 17:15:28 -0800187 // How long to delay to removal of a pending intent based request.
188 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
189 private final int mReleasePendingIntentDelayMs;
190
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800191 private Tethering mTethering;
192
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700193 private final PermissionMonitor mPermissionMonitor;
194
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700195 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700196
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700197 @GuardedBy("mVpns")
198 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700199
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700200 private boolean mLockdownEnabled;
201 private LockdownVpnTracker mLockdownTracker;
202
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700203 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
204 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700205 /** Currently active network rules by UID. */
206 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700207 /** Set of ifaces that are costly. */
208 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700209
Erik Klineda4bfa82015-04-30 12:58:40 +0900210 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700212 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700213 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800215 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216
217 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700218 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700220 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800221 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700222 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700223
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700224 private String mCurrentTcpBufferSizes;
225
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700226 private static final int ENABLED = 1;
227 private static final int DISABLED = 0;
228
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900229 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
230 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class });
231
Paul Jensenb10e37f2014-11-25 12:33:08 -0500232 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400233 // Tear down networks that have no chance (e.g. even if validated) of becoming
234 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500235 // all networks have been rematched against all NetworkRequests.
236 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400237 // Don't reap networks. This should be passed when some networks have not yet been
238 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500239 DONT_REAP
240 };
241
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700242 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700243 * used internally to change our mobile data enabled flag
244 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700245 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700246
247 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700248 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700249 * from one net to another. Clear happens when we get a new
250 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
251 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700252 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700253 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700254
Robert Greenwalt434203a2010-10-11 16:00:27 -0700255 /**
256 * used internally to reload global proxy settings
257 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700258 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700259
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700260 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400261 * PAC manager has received new port.
262 */
263 private static final int EVENT_PROXY_HAS_CHANGED = 16;
264
Robert Greenwalte049c232014-04-11 15:53:27 -0700265 /**
266 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700267 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700268 */
269 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
270
Robert Greenwalt7b816022014-04-18 15:25:25 -0700271 /**
272 * used internally when registering NetworkAgents
273 * obj = Messenger
274 */
275 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
276
Robert Greenwalt9258c642014-03-26 16:47:06 -0700277 /**
278 * used to add a network request
279 * includes a NetworkRequestInfo
280 */
281 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
282
283 /**
284 * indicates a timeout period is over - check if we had a network yet or not
285 * and if not, call the timeout calback (but leave the request live until they
286 * cancel it.
287 * includes a NetworkRequestInfo
288 */
289 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
290
291 /**
292 * used to add a network listener - no request
293 * includes a NetworkRequestInfo
294 */
295 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
296
297 /**
298 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400299 * arg1 = UID of caller
300 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700301 */
302 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
303
Robert Greenwalta67be032014-05-16 15:49:14 -0700304 /**
305 * used internally when registering NetworkFactories
306 * obj = Messenger
307 */
308 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
309
Robert Greenwalt27711812014-06-25 16:45:57 -0700310 /**
311 * used internally to expire a wakelock when transitioning
312 * from one net to another. Expire happens when we fail to find
313 * a new network (typically after 1 minute) -
314 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
315 * a replacement network.
316 */
317 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
318
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700319 /**
320 * Used internally to indicate the system is ready.
321 */
322 private static final int EVENT_SYSTEM_READY = 25;
323
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800324 /**
325 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400326 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800327 */
328 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
329
330 /**
331 * used to remove a pending intent and its associated network request.
332 * arg1 = UID of caller
333 * obj = PendingIntent
334 */
335 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
336
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900337 /**
338 * used to specify whether a network should be used even if unvalidated.
339 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
340 * arg2 = whether to remember this choice in the future (1 or 0)
341 * obj = network
342 */
343 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
344
345 /**
346 * used to ask the user to confirm a connection to an unvalidated network.
347 * obj = network
348 */
349 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700350
Erik Klineda4bfa82015-04-30 12:58:40 +0900351 /**
352 * used internally to (re)configure mobile data always-on settings.
353 */
354 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
355
Paul Jensen694f2b82015-06-17 14:15:39 -0400356 /**
357 * used to add a network listener with a pending intent
358 * obj = NetworkRequestInfo
359 */
360 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
361
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900362 /** Handler thread used for both of the handlers below. */
363 @VisibleForTesting
364 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700365 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700366 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700367 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700368 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700369
Mike Lockwood0f79b542009-08-14 14:18:49 -0400370 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800371 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400372
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700373 private PowerManager.WakeLock mNetTransitionWakeLock;
374 private String mNetTransitionWakeLockCausedBy = "";
375 private int mNetTransitionWakeLockSerialNumber;
376 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800377 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700378
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700379 // used in DBG mode to track inet condition reports
380 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
381 private ArrayList mInetLog;
382
Robert Greenwalt434203a2010-10-11 16:00:27 -0700383 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400384 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700385 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700386 private boolean mDefaultProxyDisabled = false;
387
Robert Greenwalt434203a2010-10-11 16:00:27 -0700388 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400389 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700390
Jason Monk602b2322013-07-03 17:04:33 -0400391 private PacManager mPacManager = null;
392
Erik Klineda4bfa82015-04-30 12:58:40 +0900393 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700394
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400395 private UserManager mUserManager;
396
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700397 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700398 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700399
Robert Greenwalt50393202011-06-21 17:26:14 -0700400 // the set of network types that can only be enabled by system/sig apps
401 List mProtectedNetworks;
402
John Spurlockbf991a82013-06-24 14:20:23 -0400403 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700404
Wink Savilleab9321d2013-06-29 21:10:57 -0700405 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400406
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900407 private KeepaliveTracker mKeepaliveTracker;
408
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700409 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
410 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700411 private final static int MAX_NET_ID = 65535;
412 private int mNextNetId = MIN_NET_ID;
413
Robert Greenwalt34524f02014-05-18 16:22:10 -0700414 // sequence number of NetworkRequests
415 private int mNextNetworkRequestId = 1;
416
Erik Kline7523eb32015-07-09 18:24:03 +0900417 // NetworkRequest activity String log entries.
418 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
419 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
420
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700421 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
422 private static final int MAX_VALIDATION_LOGS = 10;
423 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
424 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
425
426 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
427 synchronized(mValidationLogs) {
428 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
429 mValidationLogs.removeLast();
430 }
431 mValidationLogs.addFirst(new Pair(network, log));
432 }
433 }
434
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700435 /**
436 * Implements support for the legacy "one network per network type" model.
437 *
438 * We used to have a static array of NetworkStateTrackers, one for each
439 * network type, but that doesn't work any more now that we can have,
440 * for example, more that one wifi network. This class stores all the
441 * NetworkAgentInfo objects that support a given type, but the legacy
442 * API will only see the first one.
443 *
444 * It serves two main purposes:
445 *
446 * 1. Provide information about "the network for a given type" (since this
447 * API only supports one).
448 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
449 * the first network for a given type changes, or if the default network
450 * changes.
451 */
452 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900453
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900454 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900455 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900456
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700457 /**
458 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
459 * Each list holds references to all NetworkAgentInfos that are used to
460 * satisfy requests for that network type.
461 *
462 * This array is built out at startup such that an unsupported network
463 * doesn't get an ArrayList instance, making this a tristate:
464 * unsupported, supported but not active and active.
465 *
466 * The actual lists are populated when we scan the network types that
467 * are supported on this device.
468 */
469 private ArrayList<NetworkAgentInfo> mTypeLists[];
470
471 public LegacyTypeTracker() {
472 mTypeLists = (ArrayList<NetworkAgentInfo>[])
473 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
474 }
475
476 public void addSupportedType(int type) {
477 if (mTypeLists[type] != null) {
478 throw new IllegalStateException(
479 "legacy list for type " + type + "already initialized");
480 }
481 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
482 }
483
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700484 public boolean isTypeSupported(int type) {
485 return isNetworkTypeValid(type) && mTypeLists[type] != null;
486 }
487
488 public NetworkAgentInfo getNetworkForType(int type) {
489 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
490 return mTypeLists[type].get(0);
491 } else {
492 return null;
493 }
494 }
495
Robert Greenwalt8d482522015-06-24 13:23:42 -0700496 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900497 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900498 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700499 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900500 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900501 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900502 }
503 }
504
505 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700506 public void add(int type, NetworkAgentInfo nai) {
507 if (!isTypeSupported(type)) {
508 return; // Invalid network type.
509 }
510 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
511
512 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
513 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700514 return;
515 }
516
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900517 list.add(nai);
518
519 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900520 final boolean isDefaultNetwork = isDefaultNetwork(nai);
521 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700522 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
523 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700524 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700525 }
526
Lorenzo Colittia793a672014-07-31 23:20:17 +0900527 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900528 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900529 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
530 if (list == null || list.isEmpty()) {
531 return;
532 }
533
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900534 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900535
536 if (!list.remove(nai)) {
537 return;
538 }
539
Robert Greenwalt8d482522015-06-24 13:23:42 -0700540 final DetailedState state = DetailedState.DISCONNECTED;
541
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900542 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700543 maybeLogBroadcast(nai, state, type, wasDefault);
544 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900545 }
546
547 if (!list.isEmpty() && wasFirstNetwork) {
548 if (DBG) log("Other network available for type " + type +
549 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900550 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700551 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
552 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900553 }
554 }
555
556 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900557 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
558 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700559 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900560 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 }
562 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700563
Robert Greenwalt8d482522015-06-24 13:23:42 -0700564 // send out another legacy broadcast - currently only used for suspend/unsuspend
565 // toggle
566 public void update(NetworkAgentInfo nai) {
567 final boolean isDefault = isDefaultNetwork(nai);
568 final DetailedState state = nai.networkInfo.getDetailedState();
569 for (int type = 0; type < mTypeLists.length; type++) {
570 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700571 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700572 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700573 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700574 maybeLogBroadcast(nai, state, type, isDefault);
575 sendLegacyNetworkBroadcast(nai, state, type);
576 }
577 }
578 }
579
Lorenzo Colittia793a672014-07-31 23:20:17 +0900580 private String naiToString(NetworkAgentInfo nai) {
581 String name = (nai != null) ? nai.name() : "null";
582 String state = (nai.networkInfo != null) ?
583 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
584 "???/???";
585 return name + " " + state;
586 }
587
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700588 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900589 pw.println("mLegacyTypeTracker:");
590 pw.increaseIndent();
591 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700592 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900593 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700594 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900595 pw.println();
596 pw.println("Current state:");
597 pw.increaseIndent();
598 for (int type = 0; type < mTypeLists.length; type++) {
599 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
600 for (NetworkAgentInfo nai : mTypeLists[type]) {
601 pw.println(type + " " + naiToString(nai));
602 }
603 }
604 pw.decreaseIndent();
605 pw.decreaseIndent();
606 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700607 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700608 }
609 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
610
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900611 @VisibleForTesting
612 protected HandlerThread createHandlerThread() {
613 return new HandlerThread("ConnectivityServiceThread");
614 }
615
Jeff Sharkey899223b2012-08-04 15:24:58 -0700616 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700617 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800618 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800619
Erik Klineda4bfa82015-04-30 12:58:40 +0900620 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900621 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
Erik Kline371c7b72016-03-22 17:04:20 +0900622 new Binder(), NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +0900623 mNetworkRequests.put(mDefaultRequest, defaultNRI);
624 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900625
626 mDefaultMobileDataRequest = createInternetRequestForTransport(
627 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700628
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900629 mHandlerThread = createHandlerThread();
630 mHandlerThread.start();
631 mHandler = new InternalHandler(mHandlerThread.getLooper());
632 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700633
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800634 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800635 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
636 String id = Settings.Secure.getString(context.getContentResolver(),
637 Settings.Secure.ANDROID_ID);
638 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700639 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800640 SystemProperties.set("net.hostname", name);
641 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800642 }
643
Jeremy Joslin79294842014-12-03 17:15:28 -0800644 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
645 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
646
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700647 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700648 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800649 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700650 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700651 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700652 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700653
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700654 try {
655 mPolicyManager.registerListener(mPolicyListener);
656 } catch (RemoteException e) {
657 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700658 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700659 }
660
661 final PowerManager powerManager = (PowerManager) context.getSystemService(
662 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700663 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
664 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
665 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800666 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700667
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700668 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700669
Wink Saville51f456f2013-04-23 14:26:51 -0700670 // TODO: What is the "correct" way to do determine if this is a wifi only device?
671 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
672 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700673 String[] naStrings = context.getResources().getStringArray(
674 com.android.internal.R.array.networkAttributes);
675 for (String naString : naStrings) {
676 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700677 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700678 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700679 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800680 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700681 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700682 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700683 }
Wink Saville51f456f2013-04-23 14:26:51 -0700684 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
685 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
686 n.type);
687 continue;
688 }
Wink Saville975c8482011-04-07 14:23:45 -0700689 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800690 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700691 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700692 continue;
693 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700694 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700695
Wink Saville975c8482011-04-07 14:23:45 -0700696 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700697 mNetworksDefined++;
698 } catch(Exception e) {
699 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700700 }
701 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700702
703 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
704 if (mNetConfigs[TYPE_VPN] == null) {
705 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
706 // don't need to add TYPE_VPN to mNetConfigs.
707 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
708 mNetworksDefined++; // used only in the log() statement below.
709 }
710
Wink Saville5e56bc52013-07-29 15:00:57 -0700711 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700712
Robert Greenwalt50393202011-06-21 17:26:14 -0700713 mProtectedNetworks = new ArrayList<Integer>();
714 int[] protectedNetworks = context.getResources().getIntArray(
715 com.android.internal.R.array.config_protectedNetworks);
716 for (int p : protectedNetworks) {
717 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
718 mProtectedNetworks.add(p);
719 } else {
720 if (DBG) loge("Ignoring protectedNetwork " + p);
721 }
722 }
723
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700724 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
725 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700726
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800727 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800728
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700729 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
730
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700731 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700732 IntentFilter intentFilter = new IntentFilter();
733 intentFilter.addAction(Intent.ACTION_USER_STARTING);
734 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700735 intentFilter.addAction(Intent.ACTION_USER_ADDED);
736 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000737 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700738 mContext.registerReceiverAsUser(
739 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900740
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700741 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700742 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700743 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700744 } catch (RemoteException e) {
745 loge("Error registering observer :" + e);
746 }
747
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700748 if (DBG) {
749 mInetLog = new ArrayList();
750 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700751
Erik Klineda4bfa82015-04-30 12:58:40 +0900752 mSettingsObserver = new SettingsObserver(mContext, mHandler);
753 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800754
John Spurlockbf991a82013-06-24 14:20:23 -0400755 mDataConnectionStats = new DataConnectionStats(mContext);
756 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400757
Jason Monkdecd2952013-10-10 14:02:51 -0400758 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700759
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400760 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900761
762 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700764
Erik Klineda4bfa82015-04-30 12:58:40 +0900765 private NetworkRequest createInternetRequestForTransport(int transportType) {
766 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900767 netCap.addCapability(NET_CAPABILITY_INTERNET);
768 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900769 if (transportType > -1) {
770 netCap.addTransportType(transportType);
771 }
772 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
773 }
774
775 private void handleMobileDataAlwaysOn() {
776 final boolean enable = (Settings.Global.getInt(
777 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
778 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
779 if (enable == isEnabled) {
780 return; // Nothing to do.
781 }
782
783 if (enable) {
784 handleRegisterNetworkRequest(new NetworkRequestInfo(
Erik Kline371c7b72016-03-22 17:04:20 +0900785 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestType.REQUEST));
Erik Klineda4bfa82015-04-30 12:58:40 +0900786 } else {
787 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
788 }
789 }
790
791 private void registerSettingsCallbacks() {
792 // Watch for global HTTP proxy changes.
793 mSettingsObserver.observe(
794 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
795 EVENT_APPLY_GLOBAL_HTTP_PROXY);
796
797 // Watch for whether or not to keep mobile data always on.
798 mSettingsObserver.observe(
799 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
800 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
801 }
802
Robert Greenwalt34524f02014-05-18 16:22:10 -0700803 private synchronized int nextNetworkRequestId() {
804 return mNextNetworkRequestId++;
805 }
806
Paul Jensen67b0b072015-06-10 11:22:17 -0400807 @VisibleForTesting
808 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400809 synchronized (mNetworkForNetId) {
810 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
811 int netId = mNextNetId;
812 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
813 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500814 if (!mNetIdInUse.get(netId)) {
815 mNetIdInUse.put(netId, true);
816 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400817 }
818 }
819 }
820 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700821 }
822
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800823 private NetworkState getFilteredNetworkState(int networkType, int uid) {
824 NetworkInfo info = null;
825 LinkProperties lp = null;
826 NetworkCapabilities nc = null;
827 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800828 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800829
830 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
831 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
832 if (nai != null) {
833 synchronized (nai) {
834 info = new NetworkInfo(nai.networkInfo);
835 lp = new LinkProperties(nai.linkProperties);
836 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400837 // Network objects are outwardly immutable so there is no point to duplicating.
838 // Duplicating also precludes sharing socket factories and connection pools.
839 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800840 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800841 }
842 info.setType(networkType);
843 } else {
844 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
845 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
846 info.setIsAvailable(true);
847 lp = new LinkProperties();
848 nc = new NetworkCapabilities();
849 network = null;
850 }
851 info = getFilteredNetworkInfo(info, lp, uid);
852 }
853
Jeff Sharkey32566012014-12-02 18:30:14 -0800854 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400855 }
856
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800857 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
858 if (network == null) {
859 return null;
860 }
861 synchronized (mNetworkForNetId) {
862 return mNetworkForNetId.get(network.netId);
863 }
864 };
865
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900866 private Network[] getVpnUnderlyingNetworks(int uid) {
867 if (!mLockdownEnabled) {
868 int user = UserHandle.getUserId(uid);
869 synchronized (mVpns) {
870 Vpn vpn = mVpns.get(user);
871 if (vpn != null && vpn.appliesToUid(uid)) {
872 return vpn.getUnderlyingNetworks();
873 }
874 }
875 }
876 return null;
877 }
878
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800879 private NetworkState getUnfilteredActiveNetworkState(int uid) {
880 NetworkInfo info = null;
881 LinkProperties lp = null;
882 NetworkCapabilities nc = null;
883 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800884 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800885
Paul Jensen85cf78e2015-06-25 13:25:07 -0400886 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800887
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900888 final Network[] networks = getVpnUnderlyingNetworks(uid);
889 if (networks != null) {
890 // getUnderlyingNetworks() returns:
891 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
892 // empty array => the VPN explicitly said "no default network".
893 // non-empty array => the VPN specified one or more default networks; we use the
894 // first one.
895 if (networks.length > 0) {
896 nai = getNetworkAgentInfoForNetwork(networks[0]);
897 } else {
898 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800899 }
900 }
901
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800902 if (nai != null) {
903 synchronized (nai) {
904 info = new NetworkInfo(nai.networkInfo);
905 lp = new LinkProperties(nai.linkProperties);
906 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400907 // Network objects are outwardly immutable so there is no point to duplicating.
908 // Duplicating also precludes sharing socket factories and connection pools.
909 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800910 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800911 }
912 }
913
Jeff Sharkey32566012014-12-02 18:30:14 -0800914 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400915 }
916
917 /**
918 * Check if UID should be blocked from using the network with the given LinkProperties.
919 */
920 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700921 final boolean networkCostly;
922 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700923
Robert Greenwalt12e67352014-05-13 21:41:06 -0700924 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700925 synchronized (mRulesLock) {
926 networkCostly = mMeteredIfaces.contains(iface);
927 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700928 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700929
Jeff Sharkeydc988062015-09-14 10:09:47 -0700930 if (uidRules == RULE_REJECT_ALL) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700931 return true;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700932 } else if ((uidRules == RULE_REJECT_METERED) && networkCostly) {
933 return true;
934 } else {
935 return false;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700936 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700937 }
938
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900939 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
940 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
941 boolean removed = false;
942 boolean added = false;
943 synchronized (mBlockedAppUids) {
944 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
945 added = true;
946 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
947 removed = true;
948 }
949 }
950 if (added) log("Returning blocked NetworkInfo to uid=" + uid);
951 else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
952 }
953
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700954 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700955 * Return a filtered {@link NetworkInfo}, potentially marked
956 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800957 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700958 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800959 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
960 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400961 // network is blocked; clone and override state
962 info = new NetworkInfo(info);
963 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700964 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800965 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700966 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900967 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700968 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700969 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700970 }
971
972 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 * Return NetworkInfo for the active (i.e., connected) network interface.
974 * It is assumed that at most one network is active at a time. If more
975 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700976 * @return the info for the active network, or {@code null} if none is
977 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700979 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700981 enforceAccessPermission();
982 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800983 NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900984 NetworkInfo ni = getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
985 maybeLogBlockedNetworkInfo(ni, uid);
986 return ni;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 }
988
Paul Jensen31a94f42015-02-13 14:18:39 -0500989 @Override
990 public Network getActiveNetwork() {
991 enforceAccessPermission();
Robin Leed2baf792016-03-24 12:07:00 +0000992 return getActiveNetworkForUidInternal(Binder.getCallingUid());
993 }
994
995 @Override
996 public Network getActiveNetworkForUid(int uid) {
997 enforceConnectivityInternalPermission();
998 return getActiveNetworkForUidInternal(uid);
999 }
1000
1001 private Network getActiveNetworkForUidInternal(final int uid) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001002 final int user = UserHandle.getUserId(uid);
1003 int vpnNetId = NETID_UNSET;
1004 synchronized (mVpns) {
1005 final Vpn vpn = mVpns.get(user);
1006 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1007 }
1008 NetworkAgentInfo nai;
1009 if (vpnNetId != NETID_UNSET) {
1010 synchronized (mNetworkForNetId) {
1011 nai = mNetworkForNetId.get(vpnNetId);
1012 }
1013 if (nai != null) return nai.network;
1014 }
1015 nai = getDefaultNetwork();
1016 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
1017 return nai != null ? nai.network : null;
1018 }
1019
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001020 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1021 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001022 final int uid = Binder.getCallingUid();
1023 NetworkState state = getUnfilteredActiveNetworkState(uid);
1024 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001025 }
1026
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001027 @Override
1028 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1029 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001030 NetworkState state = getUnfilteredActiveNetworkState(uid);
1031 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001032 }
1033
1034 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 public NetworkInfo getNetworkInfo(int networkType) {
1036 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001037 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001038 if (getVpnUnderlyingNetworks(uid) != null) {
1039 // A VPN is active, so we may need to return one of its underlying networks. This
1040 // information is not available in LegacyTypeTracker, so we have to get it from
1041 // getUnfilteredActiveNetworkState.
1042 NetworkState state = getUnfilteredActiveNetworkState(uid);
1043 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1044 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1045 }
1046 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001047 NetworkState state = getFilteredNetworkState(networkType, uid);
1048 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 }
1050
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001051 @Override
1052 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1053 enforceAccessPermission();
1054 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001055 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001056 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1057 if (nai != null) {
1058 synchronized (nai) {
1059 info = new NetworkInfo(nai.networkInfo);
1060 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001061 }
1062 }
1063 return info;
1064 }
1065
1066 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 public NetworkInfo[] getAllNetworkInfo() {
1068 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001069 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001070 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1071 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001072 NetworkInfo info = getNetworkInfo(networkType);
1073 if (info != null) {
1074 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001077 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 }
1079
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001080 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001081 public Network getNetworkForType(int networkType) {
1082 enforceAccessPermission();
1083 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001084 NetworkState state = getFilteredNetworkState(networkType, uid);
1085 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1086 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001087 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001088 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001089 }
1090
1091 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001092 public Network[] getAllNetworks() {
1093 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001094 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001095 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001096 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001097 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001098 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001099 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001100 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001101 }
1102
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001103 @Override
1104 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1105 // The basic principle is: if an app's traffic could possibly go over a
1106 // network, without the app doing anything multinetwork-specific,
1107 // (hence, by "default"), then include that network's capabilities in
1108 // the array.
1109 //
1110 // In the normal case, app traffic only goes over the system's default
1111 // network connection, so that's the only network returned.
1112 //
1113 // With a VPN in force, some app traffic may go into the VPN, and thus
1114 // over whatever underlying networks the VPN specifies, while other app
1115 // traffic may go over the system default network (e.g.: a split-tunnel
1116 // VPN, or an app disallowed by the VPN), so the set of networks
1117 // returned includes the VPN's underlying networks and the system
1118 // default.
1119 enforceAccessPermission();
1120
1121 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1122
1123 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001124 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001125 if (nc != null) {
1126 result.put(nai.network, nc);
1127 }
1128
1129 if (!mLockdownEnabled) {
1130 synchronized (mVpns) {
1131 Vpn vpn = mVpns.get(userId);
1132 if (vpn != null) {
1133 Network[] networks = vpn.getUnderlyingNetworks();
1134 if (networks != null) {
1135 for (Network network : networks) {
1136 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001137 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001138 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001139 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001140 }
1141 }
1142 }
1143 }
1144 }
1145 }
1146
1147 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1148 out = result.values().toArray(out);
1149 return out;
1150 }
1151
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001152 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001153 public boolean isNetworkSupported(int networkType) {
1154 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001155 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001156 }
1157
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001158 /**
1159 * Return LinkProperties for the active (i.e., connected) default
1160 * network interface. It is assumed that at most one default network
1161 * is active at a time. If more than one is active, it is indeterminate
1162 * which will be returned.
1163 * @return the ip properties for the active network, or {@code null} if
1164 * none is active
1165 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001166 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001167 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001168 enforceAccessPermission();
1169 final int uid = Binder.getCallingUid();
1170 NetworkState state = getUnfilteredActiveNetworkState(uid);
1171 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001172 }
1173
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001174 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001175 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001176 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001177 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1178 if (nai != null) {
1179 synchronized (nai) {
1180 return new LinkProperties(nai.linkProperties);
1181 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001182 }
1183 return null;
1184 }
1185
Robert Greenwalt12e67352014-05-13 21:41:06 -07001186 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001187 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001188 public LinkProperties getLinkProperties(Network network) {
1189 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001190 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001191 if (nai != null) {
1192 synchronized (nai) {
1193 return new LinkProperties(nai.linkProperties);
1194 }
1195 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001196 return null;
1197 }
1198
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001199 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001200 if (nai != null) {
1201 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001202 if (nai.networkCapabilities != null) {
1203 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001204 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001205 }
1206 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001207 return null;
1208 }
1209
1210 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001211 public NetworkCapabilities getNetworkCapabilities(Network network) {
1212 enforceAccessPermission();
1213 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1214 }
1215
1216 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001217 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001218 // Require internal since we're handing out IMSI details
1219 enforceConnectivityInternalPermission();
1220
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001221 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001222 for (Network network : getAllNetworks()) {
1223 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1224 if (nai != null) {
1225 synchronized (nai) {
1226 final String subscriberId = (nai.networkMisc != null)
1227 ? nai.networkMisc.subscriberId : null;
1228 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1229 nai.networkCapabilities, network, subscriberId, null));
1230 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001231 }
1232 }
1233 return result.toArray(new NetworkState[result.size()]);
1234 }
1235
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001236 @Override
1237 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1238 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001239 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001240 final long token = Binder.clearCallingIdentity();
1241 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001242 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1243 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001244 try {
1245 return mPolicyManager.getNetworkQuotaInfo(state);
1246 } catch (RemoteException e) {
1247 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001248 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001249 return null;
1250 } finally {
1251 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001252 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001253 }
1254
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001255 @Override
1256 public boolean isActiveNetworkMetered() {
1257 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001258 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001259 final long token = Binder.clearCallingIdentity();
1260 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001261 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001262 } finally {
1263 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001264 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001265 }
1266
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001267 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1268 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1269 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001270 try {
1271 return mPolicyManager.isNetworkMetered(state);
1272 } catch (RemoteException e) {
1273 }
1274 }
1275 return false;
1276 }
1277
Jeff Sharkey216c1812012-08-05 14:29:23 -07001278 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1279 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001280 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001281 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001282 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001283 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001284 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001285
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001286 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 * Ensure that a network route exists to deliver traffic to the specified
1288 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001289 * @param networkType the type of the network over which traffic to the
1290 * specified host is to be routed
1291 * @param hostAddress the IP address of the host to which the route is
1292 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 * @return {@code true} on success, {@code false} on failure
1294 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001295 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001297 if (mProtectedNetworks.contains(networkType)) {
1298 enforceConnectivityInternalPermission();
1299 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001300
Chad Brubakerc0234532014-02-14 13:24:29 -08001301 InetAddress addr;
1302 try {
1303 addr = InetAddress.getByAddress(hostAddress);
1304 } catch (UnknownHostException e) {
1305 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1306 return false;
1307 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001310 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 return false;
1312 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001313
1314 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1315 if (nai == null) {
1316 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1317 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1318 } else {
1319 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1320 }
1321 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001322 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001323
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001324 DetailedState netState;
1325 synchronized (nai) {
1326 netState = nai.networkInfo.getDetailedState();
1327 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001328
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001329 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001330 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001331 log("requestRouteToHostAddress on down network "
1332 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001333 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001334 }
1335 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001337
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001338 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001339 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001340 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001341 LinkProperties lp;
1342 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001343 synchronized (nai) {
1344 lp = nai.linkProperties;
1345 netId = nai.network.netId;
1346 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001347 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001348 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1349 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001350 } finally {
1351 Binder.restoreCallingIdentity(token);
1352 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001353 }
1354
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001355 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001356 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001357 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001358 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001359 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001360 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001361 if (bestRoute.getGateway().equals(addr)) {
1362 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001363 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001364 } else {
1365 // if we will connect to this through another route, add a direct route
1366 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001367 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001368 }
1369 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001370 if (DBG) log("Adding legacy route " + bestRoute +
1371 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001372 try {
1373 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1374 } catch (Exception e) {
1375 // never crash - catch them all
1376 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001377 return false;
1378 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001379 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 }
1381
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001382 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1383 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001384 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001385 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001386 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001387 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001388 }
1389
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001390 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001391 // skip update when we've already applied rules
1392 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1393 if (oldRules == uidRules) return;
1394
1395 mUidRules.put(uid, uidRules);
1396 }
1397
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001398 // TODO: notify UID when it has requested targeted updates
1399 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001400
1401 @Override
1402 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001403 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001404 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001405 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001406 }
1407
1408 synchronized (mRulesLock) {
1409 mMeteredIfaces.clear();
1410 for (String iface : meteredIfaces) {
1411 mMeteredIfaces.add(iface);
1412 }
1413 }
1414 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001415
1416 @Override
1417 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1418 // caller is NPMS, since we only register with them
1419 if (LOGD_RULES) {
1420 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1421 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001422 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001423
1424 @Override
1425 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1426 if (LOGD_RULES) {
1427 // caller is NPMS, since we only register with them
1428 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1429 + whitelisted + ")");
1430 }
1431 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001432 };
1433
Robin Lee3b3dd942015-05-12 18:14:58 +01001434 /**
1435 * Require that the caller is either in the same user or has appropriate permission to interact
1436 * across users.
1437 *
1438 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1439 */
1440 private void enforceCrossUserPermission(int userId) {
1441 if (userId == UserHandle.getCallingUserId()) {
1442 // Not a cross-user call.
1443 return;
1444 }
1445 mContext.enforceCallingOrSelfPermission(
1446 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1447 "ConnectivityService");
1448 }
1449
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001450 private void enforceInternetPermission() {
1451 mContext.enforceCallingOrSelfPermission(
1452 android.Manifest.permission.INTERNET,
1453 "ConnectivityService");
1454 }
1455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001457 mContext.enforceCallingOrSelfPermission(
1458 android.Manifest.permission.ACCESS_NETWORK_STATE,
1459 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 }
1461
1462 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001463 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 }
1465
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001466 private void enforceTetherAccessPermission() {
1467 mContext.enforceCallingOrSelfPermission(
1468 android.Manifest.permission.ACCESS_NETWORK_STATE,
1469 "ConnectivityService");
1470 }
1471
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001472 private void enforceConnectivityInternalPermission() {
1473 mContext.enforceCallingOrSelfPermission(
1474 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1475 "ConnectivityService");
1476 }
1477
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001478 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001479 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001480 }
1481
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001482 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001483 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001484 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001485 }
1486
1487 private void sendInetConditionBroadcast(NetworkInfo info) {
1488 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1489 }
1490
Wink Saville628b0852011-08-04 15:01:58 -07001491 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001492 if (mLockdownTracker != null) {
1493 info = mLockdownTracker.augmentNetworkInfo(info);
1494 }
1495
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001496 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001497 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001498 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 if (info.isFailover()) {
1500 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1501 info.setFailover(false);
1502 }
1503 if (info.getReason() != null) {
1504 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1505 }
1506 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001507 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1508 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001510 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001511 return intent;
1512 }
1513
1514 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1515 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1516 }
1517
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001518 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001519 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1520 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1521 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001522 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001523 final long ident = Binder.clearCallingIdentity();
1524 try {
1525 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1526 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1527 } finally {
1528 Binder.restoreCallingIdentity(ident);
1529 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001530 }
1531
Mike Lockwood0f79b542009-08-14 14:18:49 -04001532 private void sendStickyBroadcast(Intent intent) {
1533 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001534 if (!mSystemReady) {
1535 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001536 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001537 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001538 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001539 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001540 }
1541
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001542 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001543 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001544 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001545 final NetworkInfo ni = intent.getParcelableExtra(
1546 ConnectivityManager.EXTRA_NETWORK_INFO);
1547 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1548 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1549 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001550 } else {
1551 BroadcastOptions opts = BroadcastOptions.makeBasic();
1552 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1553 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001554 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001555 final IBatteryStats bs = BatteryStatsService.getService();
1556 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001557 bs.noteConnectivityChanged(intent.getIntExtra(
1558 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1559 ni != null ? ni.getState().toString() : "?");
1560 } catch (RemoteException e) {
1561 }
1562 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001563 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001564 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001565 } finally {
1566 Binder.restoreCallingIdentity(ident);
1567 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001568 }
1569 }
1570
1571 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001572 loadGlobalProxy();
1573
Mike Lockwood0f79b542009-08-14 14:18:49 -04001574 synchronized(this) {
1575 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001576 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001577 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001578 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001579 }
1580 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001581 // load the global proxy at startup
1582 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001583
Robin Lee244ce8e2016-01-05 18:03:46 +00001584 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1585 // for user to unlock device too.
1586 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001587
Erik Klineda4bfa82015-04-30 12:58:40 +09001588 // Configure whether mobile data is always on.
1589 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1590
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001591 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001592
1593 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 }
1595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001597 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001598 *
1599 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001600 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001601 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001602 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1603 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001604
1605 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001606 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001607
Robert Greenwalt7b816022014-04-18 15:25:25 -07001608 if (networkAgent.networkCapabilities.hasTransport(
1609 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001610 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1611 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001612 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001613 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001614 } else if (networkAgent.networkCapabilities.hasTransport(
1615 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001616 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1617 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001618 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001619 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001620 } else {
1621 // do not track any other networks
1622 timeout = 0;
1623 }
1624
Robert Greenwalt7b816022014-04-18 15:25:25 -07001625 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001626 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001627 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001628 } catch (Exception e) {
1629 // You shall not crash!
1630 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001631 }
1632 }
1633 }
1634
1635 /**
1636 * Remove data activity tracking when network disconnects.
1637 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001638 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1639 final String iface = networkAgent.linkProperties.getInterfaceName();
1640 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001641
Robert Greenwalt7b816022014-04-18 15:25:25 -07001642 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1643 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001644 try {
1645 // the call fails silently if no idletimer setup for this interface
1646 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001647 } catch (Exception e) {
1648 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001649 }
1650 }
1651 }
1652
1653 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001654 * Reads the network specific MTU size from reources.
1655 * and set it on it's iface.
1656 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001657 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1658 final String iface = newLp.getInterfaceName();
1659 final int mtu = newLp.getMtu();
1660 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1661 if (VDBG) log("identical MTU - not setting");
1662 return;
1663 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001664
Robert Greenwalt43074032014-08-15 17:53:05 -07001665 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001666 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001667 return;
1668 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001669
w1997615afd812014-08-05 15:18:11 -07001670 // Cannot set MTU without interface name
1671 if (TextUtils.isEmpty(iface)) {
1672 loge("Setting MTU size with null iface.");
1673 return;
1674 }
1675
Robert Greenwalt7b816022014-04-18 15:25:25 -07001676 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001677 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001678 mNetd.setMtu(iface, mtu);
1679 } catch (Exception e) {
1680 Slog.e(TAG, "exception in setMtu()" + e);
1681 }
1682 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001683
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001684 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001685 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1686
1687 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001688 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001689 protected int getDefaultTcpRwnd() {
1690 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1691 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001692
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001693 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1694 if (isDefaultNetwork(nai) == false) {
1695 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001696 }
1697
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001698 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1699 String[] values = null;
1700 if (tcpBufferSizes != null) {
1701 values = tcpBufferSizes.split(",");
1702 }
1703
1704 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001705 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001706 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1707 values = tcpBufferSizes.split(",");
1708 }
1709
1710 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1711
1712 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001713 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001714
1715 final String prefix = "/sys/kernel/ipv4/tcp_";
1716 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1717 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1718 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1719 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1720 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1721 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1722 mCurrentTcpBufferSizes = tcpBufferSizes;
1723 } catch (IOException e) {
1724 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001725 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001726
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001727 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001728 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001729 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1730 if (rwndValue != 0) {
1731 SystemProperties.set(sysctlKey, rwndValue.toString());
1732 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001733 }
1734
Mattias Falk8b47b362011-08-23 14:15:13 +02001735 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001736 /*
1737 * Tell the VMs to toss their DNS caches
1738 */
1739 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1740 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001741 /*
1742 * Connectivity events can happen before boot has completed ...
1743 */
1744 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001745 final long ident = Binder.clearCallingIdentity();
1746 try {
1747 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1748 } finally {
1749 Binder.restoreCallingIdentity(ident);
1750 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001751 }
1752
Robert Greenwalt562cc542014-05-15 18:07:26 -07001753 @Override
1754 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001755 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1756 NETWORK_RESTORE_DELAY_PROP_NAME);
1757 if(restoreDefaultNetworkDelayStr != null &&
1758 restoreDefaultNetworkDelayStr.length() != 0) {
1759 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001760 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001761 } catch (NumberFormatException e) {
1762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001764 // if the system property isn't set, use the value for the apn type
1765 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1766
1767 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1768 (mNetConfigs[networkType] != null)) {
1769 ret = mNetConfigs[networkType].restoreTime;
1770 }
1771 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 }
1773
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001774 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001775 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001776 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001777 }
1778 return false;
1779 }
1780
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001781 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1782 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1783 final long DIAG_TIME_MS = 5000;
1784 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1785 // Start gathering diagnostic information.
1786 netDiags.add(new NetworkDiagnostics(
1787 nai.network,
1788 new LinkProperties(nai.linkProperties), // Must be a copy.
1789 DIAG_TIME_MS));
1790 }
1791
1792 for (NetworkDiagnostics netDiag : netDiags) {
1793 pw.println();
1794 netDiag.waitForMeasurements();
1795 netDiag.dump(pw);
1796 }
1797 }
1798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001800 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1801 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001802 if (mContext.checkCallingOrSelfPermission(
1803 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001805 pw.println("Permission Denial: can't dump ConnectivityService " +
1806 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1807 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 return;
1809 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001810
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001811 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001812 dumpNetworkDiagnostics(pw);
1813 return;
1814 }
Erik Kline379747a2015-06-05 17:47:34 +09001815
Lorenzo Colittie3805462015-06-03 11:18:24 +09001816 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001817 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001818 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001819 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001820 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001821 pw.println();
1822
Paul Jensen85cf78e2015-06-25 13:25:07 -04001823 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001824 pw.print("Active default network: ");
1825 if (defaultNai == null) {
1826 pw.println("none");
1827 } else {
1828 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001830 pw.println();
1831
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001832 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001833 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001834 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1835 pw.println(nai.toString());
1836 pw.increaseIndent();
1837 pw.println("Requests:");
1838 pw.increaseIndent();
1839 for (int i = 0; i < nai.networkRequests.size(); i++) {
1840 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001841 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001842 pw.decreaseIndent();
1843 pw.println("Lingered:");
1844 pw.increaseIndent();
1845 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1846 pw.decreaseIndent();
1847 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001848 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001849 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001850 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001851
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001852 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001853 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001854 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1855 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001856 }
1857 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001858 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001859
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001860 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001861
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001862 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001863 pw.print("mNetTransitionWakeLock: currently " +
1864 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1865 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1866 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1867 } else {
1868 pw.println(", last requested never");
1869 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001870 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001871
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001872 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001873 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001874
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001875 pw.println();
1876 mKeepaliveTracker.dump(pw);
1877
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001878 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001879
Lorenzo Colittie3805462015-06-03 11:18:24 +09001880 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001881 pw.println();
1882 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001883 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001884 for(int i = 0; i < mInetLog.size(); i++) {
1885 pw.println(mInetLog.get(i));
1886 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001887 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001888 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001889
1890 if (argsContain(args, "--short") == false) {
1891 pw.println();
1892 synchronized (mValidationLogs) {
1893 pw.println("mValidationLogs (most recent first):");
1894 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1895 pw.println(p.first);
1896 pw.increaseIndent();
1897 p.second.dump(fd, pw, args);
1898 pw.decreaseIndent();
1899 }
1900 }
Erik Kline7523eb32015-07-09 18:24:03 +09001901
1902 pw.println();
1903 pw.println("mNetworkRequestInfoLogs (most recent first):");
1904 pw.increaseIndent();
1905 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1906 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 }
1909
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001910 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001911 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001912 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001913 if (officialNai != null && officialNai.equals(nai)) return true;
1914 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001915 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001916 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001917 " - " + nai);
1918 }
1919 return false;
1920 }
1921
Paul Jensenc8b9a742014-09-30 15:37:41 -04001922 private boolean isRequest(NetworkRequest request) {
Erik Kline371c7b72016-03-22 17:04:20 +09001923 return mNetworkRequests.get(request).isRequest();
Paul Jensenc8b9a742014-09-30 15:37:41 -04001924 }
1925
Robert Greenwalt42acef32009-08-12 16:08:25 -07001926 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001927 private class NetworkStateTrackerHandler extends Handler {
1928 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001929 super(looper);
1930 }
1931
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001932 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001934 default:
1935 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07001936 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001937 handleAsyncChannelHalfConnect(msg);
1938 break;
1939 }
1940 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1941 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1942 if (nai != null) nai.asyncChannel.disconnect();
1943 break;
1944 }
1945 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1946 handleAsyncChannelDisconnected(msg);
1947 break;
1948 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001949 }
1950 return true;
1951 }
1952
1953 private void maybeHandleNetworkAgentMessage(Message msg) {
1954 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1955 if (nai == null) {
1956 if (VDBG) {
1957 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
1958 log(String.format("%s from unknown NetworkAgent", what));
1959 }
1960 return;
1961 }
1962
1963 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001964 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001965 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
1966 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1967 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
1968 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07001969 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001970 if (nai.created && !nai.networkCapabilities.equalImmutableCapabilities(
1971 networkCapabilities)) {
1972 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
1973 + nai.networkCapabilities + " -> " + networkCapabilities);
1974 }
1975 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001976 break;
1977 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001978 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001979 if (VDBG) {
1980 log("Update of LinkProperties for " + nai.name() +
1981 "; created=" + nai.created);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001982 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001983 LinkProperties oldLp = nai.linkProperties;
1984 synchronized (nai) {
1985 nai.linkProperties = (LinkProperties)msg.obj;
1986 }
1987 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001988 break;
1989 }
1990 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001991 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001992 updateNetworkInfo(nai, info);
1993 break;
1994 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001995 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07001996 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001997 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001998 break;
1999 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002000 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002001 try {
2002 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002003 } catch (Exception e) {
2004 // Never crash!
2005 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002006 }
2007 break;
2008 }
2009 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002010 try {
2011 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002012 } catch (Exception e) {
2013 // Never crash!
2014 loge("Exception in removeVpnUidRanges: " + e);
2015 }
2016 break;
2017 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002018 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002019 if (nai.created && !nai.networkMisc.explicitlySelected) {
2020 loge("ERROR: created network explicitly selected.");
2021 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002022 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002023 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002024 break;
2025 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002026 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002027 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2028 break;
2029 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002030 }
2031 }
2032
2033 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2034 switch (msg.what) {
2035 default:
2036 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002037 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002038 final NetworkAgentInfo nai;
2039 synchronized (mNetworkForNetId) {
2040 nai = mNetworkForNetId.get(msg.arg2);
2041 }
2042 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002043 final boolean valid =
2044 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen232437312016-04-06 09:51:26 -04002045 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2046 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002047 if (valid != nai.lastValidated) {
2048 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002049 nai.lastValidated = valid;
2050 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002051 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002052 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2053 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002054 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002055 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002056 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002057 Bundle redirectUrlBundle = new Bundle();
2058 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002059 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002060 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002061 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002062 0, redirectUrlBundle);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002063 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002064 break;
2065 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002066 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002067 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002068 if (isLiveNetworkAgent(nai, msg.what)) {
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002069 handleLingerComplete(nai);
2070 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002071 break;
2072 }
Paul Jensen869868be2014-05-15 10:33:05 -04002073 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002074 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002075 final boolean visible = (msg.arg1 != 0);
2076 final NetworkAgentInfo nai;
2077 synchronized (mNetworkForNetId) {
2078 nai = mNetworkForNetId.get(netId);
2079 }
2080 // If captive portal status has changed, update capabilities.
2081 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2082 nai.lastCaptivePortalDetected = visible;
2083 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002084 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002085 }
2086 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002087 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002088 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002089 if (nai == null) {
2090 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2091 break;
2092 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002093 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002094 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2095 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002096 }
Paul Jensen869868be2014-05-15 10:33:05 -04002097 break;
2098 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002099 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002100 return true;
2101 }
2102
2103 @Override
2104 public void handleMessage(Message msg) {
2105 if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) {
2106 maybeHandleNetworkAgentMessage(msg);
2107 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002108 }
2109 }
2110
Paul Jensen85cf78e2015-06-25 13:25:07 -04002111 private void linger(NetworkAgentInfo nai) {
2112 nai.lingering = true;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002113 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_LINGER);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002114 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2115 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2116 }
2117
Paul Jensen0cc17322014-11-25 15:26:53 -05002118 // Cancel any lingering so the linger timeout doesn't teardown a network.
2119 // This should be called when a network begins satisfying a NetworkRequest.
2120 // Note: depending on what state the NetworkMonitor is in (e.g.,
2121 // if it's awaiting captive portal login, or if validation failed), this
2122 // may trigger a re-evaluation of the network.
2123 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002124 nai.networkLingered.clear();
2125 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002126 nai.lingering = false;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002127 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_UNLINGER);
Paul Jensen0cc17322014-11-25 15:26:53 -05002128 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002129 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2130 }
2131
Robert Greenwalt7b816022014-04-18 15:25:25 -07002132 private void handleAsyncChannelHalfConnect(Message msg) {
2133 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002134 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002135 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2136 if (VDBG) log("NetworkFactory connected");
2137 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002138 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Erik Kline371c7b72016-03-22 17:04:20 +09002139 if (!nri.isRequest()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002140 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002141 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002142 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002143 }
2144 } else {
2145 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002146 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002147 }
2148 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2149 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2150 if (VDBG) log("NetworkAgent connected");
2151 // A network agent has requested a connection. Establish the connection.
2152 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2153 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2154 } else {
2155 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002156 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002157 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002158 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002159 synchronized (mNetworkForNetId) {
2160 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002161 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002162 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002163 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002164 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002165 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002166 }
2167 }
2168 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002169
Robert Greenwalt7b816022014-04-18 15:25:25 -07002170 private void handleAsyncChannelDisconnected(Message msg) {
2171 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2172 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002173 if (DBG) {
2174 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2175 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002176 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002177 // TODO - if we move the logic to the network agent (have them disconnect
2178 // because they lost all their requests or because their score isn't good)
2179 // then they would disconnect organically, report their new state and then
2180 // disconnect the channel.
2181 if (nai.networkInfo.isConnected()) {
2182 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2183 null, null);
2184 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002185 final boolean wasDefault = isDefaultNetwork(nai);
2186 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002187 mDefaultInetConditionPublished = 0;
2188 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002189 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002190 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2191 // by other networks that are already connected. Perhaps that can be done by
2192 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2193 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002194 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002195 mKeepaliveTracker.handleStopAllKeepalives(nai,
2196 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002197 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002198 mNetworkAgentInfos.remove(msg.replyTo);
2199 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002200 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002201 // Remove the NetworkAgent, but don't mark the netId as
2202 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002203 mNetworkForNetId.remove(nai.network.netId);
2204 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002205 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002206 for (int i = 0; i < nai.networkRequests.size(); i++) {
2207 NetworkRequest request = nai.networkRequests.valueAt(i);
2208 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2209 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2210 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002211 sendUpdatedScoreToFactories(request, 0);
2212 }
2213 }
2214 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2215 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002216 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002217 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002218 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002219 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002220 rematchAllNetworksAndRequests(null, 0);
Pierre Imai04e222252016-04-12 18:02:58 +09002221 if (wasDefault && getDefaultNetwork() == null) {
2222 // Log that we lost the default network and there is no replacement.
Hugo Benichi5f16f762016-04-20 12:09:33 +09002223 logDefaultNetworkEvent(null, nai);
Pierre Imai04e222252016-04-12 18:02:58 +09002224 }
Paul Jensen62d30802015-06-17 14:42:30 -04002225 if (nai.created) {
2226 // Tell netd to clean up the configuration for this network
2227 // (routing rules, DNS, etc).
2228 // This may be slow as it requires a lot of netd shelling out to ip and
2229 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2230 // after we've rematched networks with requests which should make a potential
2231 // fallback network the default or requested a new network from the
2232 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2233 // long time.
2234 try {
2235 mNetd.removeNetwork(nai.network.netId);
2236 } catch (Exception e) {
2237 loge("Exception removing network: " + e);
2238 }
2239 }
2240 synchronized (mNetworkForNetId) {
2241 mNetIdInUse.delete(nai.network.netId);
2242 }
2243 } else {
2244 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2245 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002246 }
2247 }
2248
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002249 // If this method proves to be too slow then we can maintain a separate
2250 // pendingIntent => NetworkRequestInfo map.
2251 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2252 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2253 Intent intent = pendingIntent.getIntent();
2254 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2255 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2256 if (existingPendingIntent != null &&
2257 existingPendingIntent.getIntent().filterEquals(intent)) {
2258 return entry.getValue();
2259 }
2260 }
2261 return null;
2262 }
2263
2264 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2265 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2266
2267 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2268 if (existingRequest != null) { // remove the existing request.
2269 if (DBG) log("Replacing " + existingRequest.request + " with "
2270 + nri.request + " because their intents matched.");
2271 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2272 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002273 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002274 }
2275
Erik Klineda4bfa82015-04-30 12:58:40 +09002276 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002277 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002278 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002279 if (!nri.isRequest()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002280 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002281 if (nri.request.networkCapabilities.hasSignalStrength() &&
2282 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2283 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002284 }
2285 }
2286 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002287 rematchAllNetworksAndRequests(null, 0);
Erik Kline371c7b72016-03-22 17:04:20 +09002288 if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002289 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002290 }
2291 }
2292
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002293 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2294 int callingUid) {
2295 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2296 if (nri != null) {
2297 handleReleaseNetworkRequest(nri.request, callingUid);
2298 }
2299 }
2300
Paul Jensen99364842014-12-09 11:43:45 -05002301 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002302 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2303 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002304 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002305 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002306 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2307 // If this Network is already the highest scoring Network for a request, or if
2308 // there is hope for it to become one if it validated, then it is needed.
Erik Kline371c7b72016-03-22 17:04:20 +09002309 if (nri.isRequest() && nai.satisfies(nri.request) &&
Paul Jensene0988542015-06-25 15:30:08 -04002310 (nai.networkRequests.get(nri.request.requestId) != null ||
2311 // Note that this catches two important cases:
2312 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2313 // is currently satisfying the request. This is desirable when
2314 // cellular ends up validating but WiFi does not.
2315 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002316 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002317 // WiFi ends up validating and out scoring cellular.
2318 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2319 nai.getCurrentScoreAsValidated())) {
2320 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002321 }
2322 }
Paul Jensene0988542015-06-25 15:30:08 -04002323 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002324 }
2325
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002326 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2327 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002328 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002329 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002330 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2331 return;
2332 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002333 if (VDBG || (DBG && nri.isRequest())) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002334 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002335 mNetworkRequests.remove(request);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002336 synchronized (mUidToNetworkRequestCount) {
2337 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2338 if (requests < 1) {
2339 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2340 nri.mUid);
2341 } else if (requests == 1) {
2342 mUidToNetworkRequestCount.removeAt(
2343 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2344 } else {
2345 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2346 }
2347 }
Erik Kline7523eb32015-07-09 18:24:03 +09002348 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002349 if (nri.isRequest()) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002350 // Find all networks that are satisfying this request and remove the request
2351 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002352 // TODO - it's my understanding that for a request there is only a single
2353 // network satisfying it, so this loop is wasteful
2354 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002355 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2356 if (nai.networkRequests.get(nri.request.requestId) != null) {
2357 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002358 if (VDBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002359 log(" Removing from current network " + nai.name() +
2360 ", leaving " + nai.networkRequests.size() +
2361 " requests.");
2362 }
Paul Jensen99364842014-12-09 11:43:45 -05002363 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002364 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002365 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002366 } else {
2367 // suspect there should only be one pass through here
2368 // but if any were kept do the check below
2369 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002370 }
2371 }
2372 }
2373
Robert Greenwalt51481852015-01-08 14:43:31 -08002374 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2375 if (nai != null) {
2376 mNetworkForRequestId.remove(nri.request.requestId);
2377 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002378 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002379 // that a network connected to serve it, even though the network was already
2380 // connected. Now that this request has gone away, we might have to pretend
2381 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002382 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002383 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2384 boolean doRemove = true;
2385 if (wasKept) {
2386 // check if any of the remaining requests for this network are for the
2387 // same legacy type - if so, don't remove the nai
2388 for (int i = 0; i < nai.networkRequests.size(); i++) {
2389 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2390 if (otherRequest.legacyType == nri.request.legacyType &&
2391 isRequest(otherRequest)) {
2392 if (DBG) log(" still have other legacy request - leaving");
2393 doRemove = false;
2394 }
2395 }
2396 }
2397
2398 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002399 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002400 }
2401 }
2402
Robert Greenwalta67be032014-05-16 15:49:14 -07002403 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002404 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2405 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002406 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002407 } else {
2408 // listens don't have a singular affectedNetwork. Check all networks to see
2409 // if this listen request applies and remove it.
2410 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2411 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002412 if (nri.request.networkCapabilities.hasSignalStrength() &&
2413 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2414 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002415 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002416 }
2417 }
2418 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2419 }
2420 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002421
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002422 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2423 enforceConnectivityInternalPermission();
2424 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2425 accept ? 1 : 0, always ? 1: 0, network));
2426 }
2427
2428 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2429 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2430 " accept=" + accept + " always=" + always);
2431
2432 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2433 if (nai == null) {
2434 // Nothing to do.
2435 return;
2436 }
2437
2438 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002439 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002440 return;
2441 }
2442
2443 if (!nai.networkMisc.explicitlySelected) {
2444 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2445 }
2446
2447 if (accept != nai.networkMisc.acceptUnvalidated) {
2448 int oldScore = nai.getCurrentScore();
2449 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002450 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002451 sendUpdatedScoreToFactories(nai);
2452 }
2453
2454 if (always) {
2455 nai.asyncChannel.sendMessage(
2456 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2457 }
2458
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002459 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002460 // Tell the NetworkAgent to not automatically reconnect to the network.
2461 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2462 // Teardown the nework.
2463 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002464 }
2465
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002466 }
2467
2468 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002469 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002470 mHandler.sendMessageDelayed(
2471 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2472 PROMPT_UNVALIDATED_DELAY_MS);
2473 }
2474
2475 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002476 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002477 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2478
2479 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2480 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002481 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002482 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002483 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2484 return;
2485 }
2486
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002487 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002488 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002489 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2490 intent.setClassName("com.android.settings",
2491 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002492
2493 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2494 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2495 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002496 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002497 }
2498
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002499 private class InternalHandler extends Handler {
2500 public InternalHandler(Looper looper) {
2501 super(looper);
2502 }
2503
2504 @Override
2505 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002506 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002507 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002508 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002509 String causedBy = null;
2510 synchronized (ConnectivityService.this) {
2511 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2512 mNetTransitionWakeLock.isHeld()) {
2513 mNetTransitionWakeLock.release();
2514 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002515 } else {
2516 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002517 }
2518 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002519 if (VDBG) {
2520 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2521 log("Failed to find a new network - expiring NetTransition Wakelock");
2522 } else {
2523 log("NetTransition Wakelock (" +
2524 (causedBy == null ? "unknown" : causedBy) +
2525 " cleared because we found a replacement network");
2526 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002527 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002528 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002529 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002530 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002531 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002532 break;
2533 }
Jason Monkdecd2952013-10-10 14:02:51 -04002534 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002535 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002536 break;
2537 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002538 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002539 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2540 break;
2541 }
2542 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2543 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002544 break;
2545 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002546 case EVENT_REGISTER_NETWORK_AGENT: {
2547 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2548 break;
2549 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002550 case EVENT_REGISTER_NETWORK_REQUEST:
2551 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002552 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002553 break;
2554 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002555 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2556 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002557 handleRegisterNetworkRequestWithIntent(msg);
2558 break;
2559 }
2560 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2561 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2562 break;
2563 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002564 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002565 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002566 break;
2567 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002568 case EVENT_SET_ACCEPT_UNVALIDATED: {
2569 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2570 break;
2571 }
2572 case EVENT_PROMPT_UNVALIDATED: {
2573 handlePromptUnvalidated((Network) msg.obj);
2574 break;
2575 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002576 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2577 handleMobileDataAlwaysOn();
2578 break;
2579 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002580 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2581 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2582 mKeepaliveTracker.handleStartKeepalive(msg);
2583 break;
2584 }
2585 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2586 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2587 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2588 int slot = msg.arg1;
2589 int reason = msg.arg2;
2590 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2591 break;
2592 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002593 case EVENT_SYSTEM_READY: {
2594 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2595 nai.networkMonitor.systemReady = true;
2596 }
2597 break;
2598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 }
2600 }
2601 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002602
2603 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002604 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002605 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002606 if (isTetheringSupported()) {
2607 return mTethering.tether(iface);
2608 } else {
2609 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2610 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002611 }
2612
2613 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002614 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002615 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002616
2617 if (isTetheringSupported()) {
2618 return mTethering.untether(iface);
2619 } else {
2620 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2621 }
2622 }
2623
2624 // javadoc from interface
2625 public int getLastTetherError(String iface) {
2626 enforceTetherAccessPermission();
2627
2628 if (isTetheringSupported()) {
2629 return mTethering.getLastTetherError(iface);
2630 } else {
2631 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2632 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002633 }
2634
2635 // TODO - proper iface API for selection by property, inspection, etc
2636 public String[] getTetherableUsbRegexs() {
2637 enforceTetherAccessPermission();
2638 if (isTetheringSupported()) {
2639 return mTethering.getTetherableUsbRegexs();
2640 } else {
2641 return new String[0];
2642 }
2643 }
2644
2645 public String[] getTetherableWifiRegexs() {
2646 enforceTetherAccessPermission();
2647 if (isTetheringSupported()) {
2648 return mTethering.getTetherableWifiRegexs();
2649 } else {
2650 return new String[0];
2651 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002652 }
2653
Danica Chang6fdd0c62010-08-11 14:54:43 -07002654 public String[] getTetherableBluetoothRegexs() {
2655 enforceTetherAccessPermission();
2656 if (isTetheringSupported()) {
2657 return mTethering.getTetherableBluetoothRegexs();
2658 } else {
2659 return new String[0];
2660 }
2661 }
2662
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002663 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002664 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002665 if (isTetheringSupported()) {
2666 return mTethering.setUsbTethering(enable);
2667 } else {
2668 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2669 }
2670 }
2671
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002672 // TODO - move iface listing, queries, etc to new module
2673 // javadoc from interface
2674 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002675 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002676 return mTethering.getTetherableIfaces();
2677 }
2678
2679 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002680 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002681 return mTethering.getTetheredIfaces();
2682 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002683
Robert Greenwalt5a735062010-03-02 17:25:02 -08002684 public String[] getTetheringErroredIfaces() {
2685 enforceTetherAccessPermission();
2686 return mTethering.getErroredIfaces();
2687 }
2688
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002689 public String[] getTetheredDhcpRanges() {
2690 enforceConnectivityInternalPermission();
2691 return mTethering.getTetheredDhcpRanges();
2692 }
2693
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002694 // if ro.tether.denied = true we default to no tethering
2695 // gservices could set the secure setting to 1 though to enable it on a build where it
2696 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002697 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002698 public boolean isTetheringSupported() {
2699 enforceTetherAccessPermission();
2700 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002701 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002702 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2703 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002704 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2705 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002706 mTethering.getTetherableWifiRegexs().length != 0 ||
2707 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2708 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002709 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002710
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002711 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002712 public void startTethering(int type, ResultReceiver receiver,
2713 boolean showProvisioningUi) {
2714 ConnectivityManager.enforceTetherChangePermission(mContext);
2715 if (!isTetheringSupported()) {
2716 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2717 return;
2718 }
2719 mTethering.startTethering(type, receiver, showProvisioningUi);
2720 }
2721
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002722 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002723 public void stopTethering(int type) {
2724 ConnectivityManager.enforceTetherChangePermission(mContext);
2725 mTethering.stopTethering(type);
2726 }
2727
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002728 // Called when we lose the default network and have no replacement yet.
2729 // This will automatically be cleared after X seconds or a new default network
2730 // becomes CONNECTED, whichever happens first. The timer is started by the
2731 // first caller and not restarted by subsequent callers.
2732 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002733 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002734 synchronized (this) {
2735 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002736 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002737 mNetTransitionWakeLock.acquire();
2738 mNetTransitionWakeLockCausedBy = forWhom;
2739 }
2740 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002741 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002742 mNetTransitionWakeLockTimeout);
2743 return;
2744 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002745
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002746 // 100 percent is full good, 0 is full bad.
2747 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002748 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002749 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002750 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002751 }
2752
Paul Jensenbfd17b72015-04-07 12:43:13 -04002753 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002754 enforceAccessPermission();
2755 enforceInternetPermission();
2756
Paul Jensenbfd17b72015-04-07 12:43:13 -04002757 NetworkAgentInfo nai;
2758 if (network == null) {
2759 nai = getDefaultNetwork();
2760 } else {
2761 nai = getNetworkAgentInfoForNetwork(network);
2762 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002763 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2764 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2765 return;
2766 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002767 // Revalidate if the app report does not match our current validated state.
2768 if (hasConnectivity == nai.lastValidated) return;
2769 final int uid = Binder.getCallingUid();
2770 if (DBG) {
2771 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2772 ") by " + uid);
2773 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002774 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002775 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2776 // which isn't meant to work on uncreated networks.
2777 if (!nai.created) return;
2778
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002779 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002780
2781 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2782 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002783 }
2784
Paul Jensencee9b512015-05-06 07:32:40 -04002785 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002786 // this information is already available as a world read/writable jvm property
2787 // so this API change wouldn't have a benifit. It also breaks the passing
2788 // of proxy info to all the JVMs.
2789 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002790 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002791 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002792 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2793 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002794 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002795 }
2796
Paul Jensencee9b512015-05-06 07:32:40 -04002797 public ProxyInfo getProxyForNetwork(Network network) {
2798 if (network == null) return getDefaultProxy();
2799 final ProxyInfo globalProxy = getGlobalProxy();
2800 if (globalProxy != null) return globalProxy;
2801 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2802 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2803 // caller may not have.
2804 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2805 if (nai == null) return null;
2806 synchronized (nai) {
2807 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2808 if (proxyInfo == null) return null;
2809 return new ProxyInfo(proxyInfo);
2810 }
2811 }
2812
Paul Jensene0bef712014-12-10 15:12:18 -05002813 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2814 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2815 // proxy is null then there is no proxy in place).
2816 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2817 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2818 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2819 proxy = null;
2820 }
2821 return proxy;
2822 }
2823
2824 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2825 // better for determining if a new proxy broadcast is necessary:
2826 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2827 // avoid unnecessary broadcasts.
2828 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2829 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2830 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2831 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2832 // all set.
2833 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2834 a = canonicalizeProxyInfo(a);
2835 b = canonicalizeProxyInfo(b);
2836 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2837 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2838 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2839 }
2840
Jason Monk207900c2014-04-25 15:00:09 -04002841 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002842 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002843
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002844 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002845 if (proxyProperties == mGlobalProxy) return;
2846 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2847 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2848
2849 String host = "";
2850 int port = 0;
2851 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002852 String pacFileUrl = "";
2853 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002854 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002855 if (!proxyProperties.isValid()) {
2856 if (DBG)
2857 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2858 return;
2859 }
Jason Monk207900c2014-04-25 15:00:09 -04002860 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002861 host = mGlobalProxy.getHost();
2862 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002863 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002864 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002865 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002866 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002867 } else {
2868 mGlobalProxy = null;
2869 }
2870 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002871 final long token = Binder.clearCallingIdentity();
2872 try {
2873 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2874 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2875 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2876 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002877 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002878 } finally {
2879 Binder.restoreCallingIdentity(token);
2880 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002881
Jason Monkcf0f97a2014-10-02 15:39:38 -04002882 if (mGlobalProxy == null) {
2883 proxyProperties = mDefaultProxy;
2884 }
2885 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002886 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002887 }
2888
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002889 private void loadGlobalProxy() {
2890 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002891 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2892 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2893 String exclList = Settings.Global.getString(res,
2894 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002895 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2896 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002897 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002898 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002899 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002900 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002901 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002902 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002903 if (!proxyProperties.isValid()) {
2904 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2905 return;
2906 }
2907
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002908 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002909 mGlobalProxy = proxyProperties;
2910 }
2911 }
2912 }
2913
Jason Monk207900c2014-04-25 15:00:09 -04002914 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002915 // this information is already available as a world read/writable jvm property
2916 // so this API change wouldn't have a benifit. It also breaks the passing
2917 // of proxy info to all the JVMs.
2918 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002919 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002920 return mGlobalProxy;
2921 }
2922 }
2923
Jason Monk207900c2014-04-25 15:00:09 -04002924 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002925 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002926 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002927 proxy = null;
2928 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002929 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002930 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002931 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002932 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002933 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2934 return;
2935 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002936
2937 // This call could be coming from the PacManager, containing the port of the local
2938 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2939 // global (to get the correct local port), and send a broadcast.
2940 // TODO: Switch PacManager to have its own message to send back rather than
2941 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002942 if ((mGlobalProxy != null) && (proxy != null)
2943 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002944 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2945 mGlobalProxy = proxy;
2946 sendProxyBroadcast(mGlobalProxy);
2947 return;
2948 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002949 mDefaultProxy = proxy;
2950
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002951 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002952 if (!mDefaultProxyDisabled) {
2953 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002954 }
2955 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002956 }
2957
Paul Jensene0bef712014-12-10 15:12:18 -05002958 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2959 // This method gets called when any network changes proxy, but the broadcast only ever contains
2960 // the default proxy (even if it hasn't changed).
2961 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2962 // world where an app might be bound to a non-default network.
2963 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2964 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2965 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2966
2967 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2968 sendProxyBroadcast(getDefaultProxy());
2969 }
2970 }
2971
Robert Greenwalt434203a2010-10-11 16:00:27 -07002972 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002973 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2974 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002975 if (!TextUtils.isEmpty(proxy)) {
2976 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002977 if (data.length == 0) {
2978 return;
2979 }
2980
Robert Greenwalt434203a2010-10-11 16:00:27 -07002981 String proxyHost = data[0];
2982 int proxyPort = 8080;
2983 if (data.length > 1) {
2984 try {
2985 proxyPort = Integer.parseInt(data[1]);
2986 } catch (NumberFormatException e) {
2987 return;
2988 }
2989 }
Jason Monk207900c2014-04-25 15:00:09 -04002990 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002991 setGlobalProxy(p);
2992 }
2993 }
2994
Jason Monk207900c2014-04-25 15:00:09 -04002995 private void sendProxyBroadcast(ProxyInfo proxy) {
2996 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002997 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002998 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002999 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003000 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3001 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003002 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003003 final long ident = Binder.clearCallingIdentity();
3004 try {
3005 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3006 } finally {
3007 Binder.restoreCallingIdentity(ident);
3008 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003009 }
3010
3011 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003012 final private HashMap<Uri, Integer> mUriEventMap;
3013 final private Context mContext;
3014 final private Handler mHandler;
3015
3016 SettingsObserver(Context context, Handler handler) {
3017 super(null);
3018 mUriEventMap = new HashMap<Uri, Integer>();
3019 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003020 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003021 }
3022
Erik Klineda4bfa82015-04-30 12:58:40 +09003023 void observe(Uri uri, int what) {
3024 mUriEventMap.put(uri, what);
3025 final ContentResolver resolver = mContext.getContentResolver();
3026 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003027 }
3028
3029 @Override
3030 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003031 Slog.wtf(TAG, "Should never be reached.");
3032 }
3033
3034 @Override
3035 public void onChange(boolean selfChange, Uri uri) {
3036 final Integer what = mUriEventMap.get(uri);
3037 if (what != null) {
3038 mHandler.obtainMessage(what.intValue()).sendToTarget();
3039 } else {
3040 loge("No matching event to send for URI=" + uri);
3041 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003042 }
3043 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003044
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003045 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003046 Slog.d(TAG, s);
3047 }
3048
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003049 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003050 Slog.e(TAG, s);
3051 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003052
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003053 private static <T> T checkNotNull(T value, String message) {
3054 if (value == null) {
3055 throw new NullPointerException(message);
3056 }
3057 return value;
3058 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003059
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003060 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003061 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003062 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3063 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3064 *
3065 * @param oldPackage Package name of the application which currently controls VPN, which will
3066 * be replaced. If there is no such application, this should should either be
3067 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3068 * @param newPackage Package name of the application which should gain control of VPN, or
3069 * {@code null} to disable.
3070 * @param userId User for whom to prepare the new VPN.
3071 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003072 * @hide
3073 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003074 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003075 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3076 int userId) {
3077 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003078 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003079
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003080 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003081 Vpn vpn = mVpns.get(userId);
3082 if (vpn != null) {
3083 return vpn.prepare(oldPackage, newPackage);
3084 } else {
3085 return false;
3086 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003087 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003088 }
3089
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003090 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003091 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3092 * This method is used by system-privileged apps.
3093 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3094 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3095 *
3096 * @param packageName The package for which authorization state should change.
3097 * @param userId User for whom {@code packageName} is installed.
3098 * @param authorized {@code true} if this app should be able to start a VPN connection without
3099 * explicit user approval, {@code false} if not.
3100 *
Jeff Davidson05542602014-08-11 14:07:27 -07003101 * @hide
3102 */
3103 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003104 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3105 enforceCrossUserPermission(userId);
3106
Jeff Davidson05542602014-08-11 14:07:27 -07003107 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003108 Vpn vpn = mVpns.get(userId);
3109 if (vpn != null) {
3110 vpn.setPackageAuthorization(packageName, authorized);
3111 }
Jeff Davidson05542602014-08-11 14:07:27 -07003112 }
3113 }
3114
3115 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003116 * Configure a TUN interface and return its file descriptor. Parameters
3117 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003118 * and not available in ConnectivityManager. Permissions are checked in
3119 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003120 * @hide
3121 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003122 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003123 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003124 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003125 int user = UserHandle.getUserId(Binder.getCallingUid());
3126 synchronized(mVpns) {
3127 return mVpns.get(user).establish(config);
3128 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003129 }
3130
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003131 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003132 * Start legacy VPN, controlling native daemons as needed. Creates a
3133 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003134 */
3135 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003136 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003137 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003138 final LinkProperties egress = getActiveLinkProperties();
3139 if (egress == null) {
3140 throw new IllegalStateException("Missing active network connection");
3141 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003142 int user = UserHandle.getUserId(Binder.getCallingUid());
3143 synchronized(mVpns) {
3144 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3145 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003146 }
3147
3148 /**
3149 * Return the information of the ongoing legacy VPN. This method is used
3150 * by VpnSettings and not available in ConnectivityManager. Permissions
3151 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003152 */
3153 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003154 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3155 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003156 if (mLockdownEnabled) {
3157 return null;
3158 }
3159
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003160 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003161 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003162 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003163 }
3164
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003165 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003166 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3167 * and not available in ConnectivityManager.
3168 */
3169 @Override
3170 public VpnInfo[] getAllVpnInfo() {
3171 enforceConnectivityInternalPermission();
3172 if (mLockdownEnabled) {
3173 return new VpnInfo[0];
3174 }
3175
3176 synchronized(mVpns) {
3177 List<VpnInfo> infoList = new ArrayList<>();
3178 for (int i = 0; i < mVpns.size(); i++) {
3179 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3180 if (info != null) {
3181 infoList.add(info);
3182 }
3183 }
3184 return infoList.toArray(new VpnInfo[infoList.size()]);
3185 }
3186 }
3187
3188 /**
3189 * @return VPN information for accounting, or null if we can't retrieve all required
3190 * information, e.g primary underlying iface.
3191 */
3192 @Nullable
3193 private VpnInfo createVpnInfo(Vpn vpn) {
3194 VpnInfo info = vpn.getVpnInfo();
3195 if (info == null) {
3196 return null;
3197 }
3198 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3199 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3200 // the underlyingNetworks list.
3201 if (underlyingNetworks == null) {
3202 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3203 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3204 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3205 }
3206 } else if (underlyingNetworks.length > 0) {
3207 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3208 if (linkProperties != null) {
3209 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3210 }
3211 }
3212 return info.primaryUnderlyingIface == null ? null : info;
3213 }
3214
3215 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003216 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3217 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003218 * Permissions are checked in Vpn class.
3219 * @hide
3220 */
3221 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003222 public VpnConfig getVpnConfig(int userId) {
3223 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003224 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003225 Vpn vpn = mVpns.get(userId);
3226 if (vpn != null) {
3227 return vpn.getVpnConfig();
3228 } else {
3229 return null;
3230 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003231 }
3232 }
3233
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003234 @Override
3235 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003236 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3237 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3238 return false;
3239 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003240
3241 // Tear down existing lockdown if profile was removed
3242 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3243 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003244 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3245 final VpnProfile profile = VpnProfile.decode(
3246 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003247 if (profile == null) {
3248 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3249 setLockdownTracker(null);
3250 return true;
3251 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003252 int user = UserHandle.getUserId(Binder.getCallingUid());
3253 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003254 Vpn vpn = mVpns.get(user);
3255 if (vpn == null) {
3256 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3257 return false;
3258 }
3259 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003260 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003261 } else {
3262 setLockdownTracker(null);
3263 }
3264
3265 return true;
3266 }
3267
3268 /**
3269 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3270 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3271 */
3272 private void setLockdownTracker(LockdownVpnTracker tracker) {
3273 // Shutdown any existing tracker
3274 final LockdownVpnTracker existing = mLockdownTracker;
3275 mLockdownTracker = null;
3276 if (existing != null) {
3277 existing.shutdown();
3278 }
3279
3280 try {
3281 if (tracker != null) {
3282 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003283 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003284 mLockdownTracker = tracker;
3285 mLockdownTracker.init();
3286 } else {
3287 mNetd.setFirewallEnabled(false);
3288 }
3289 } catch (RemoteException e) {
3290 // ignored; NMS lives inside system_server
3291 }
3292 }
3293
3294 private void throwIfLockdownEnabled() {
3295 if (mLockdownEnabled) {
3296 throw new IllegalStateException("Unavailable in lockdown mode");
3297 }
3298 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003299
Robin Lee244ce8e2016-01-05 18:03:46 +00003300 /**
3301 * Sets up or tears down the always-on VPN for user {@param user} as appropriate.
3302 *
3303 * @return {@code false} in case of errors; {@code true} otherwise.
3304 */
3305 private boolean updateAlwaysOnVpn(int user) {
3306 final String lockdownPackage = getAlwaysOnVpnPackage(user);
3307 if (lockdownPackage == null) {
3308 return true;
3309 }
3310
3311 // Create an intent to start the VPN service declared in the app's manifest.
3312 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
3313 serviceIntent.setPackage(lockdownPackage);
3314
3315 try {
3316 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(user)) != null;
3317 } catch (RuntimeException e) {
3318 return false;
3319 }
3320 }
3321
3322 @Override
3323 public boolean setAlwaysOnVpnPackage(int userId, String packageName) {
3324 enforceConnectivityInternalPermission();
3325 enforceCrossUserPermission(userId);
3326
3327 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3328 if (LockdownVpnTracker.isEnabled()) {
3329 return false;
3330 }
3331
3332 // If the current VPN package is the same as the new one, this is a no-op
3333 final String oldPackage = getAlwaysOnVpnPackage(userId);
3334 if (TextUtils.equals(oldPackage, packageName)) {
3335 return true;
3336 }
3337
3338 synchronized (mVpns) {
3339 Vpn vpn = mVpns.get(userId);
3340 if (vpn == null) {
3341 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3342 return false;
3343 }
3344 if (!vpn.setAlwaysOnPackage(packageName)) {
3345 return false;
3346 }
3347 if (!updateAlwaysOnVpn(userId)) {
3348 vpn.setAlwaysOnPackage(null);
3349 return false;
3350 }
3351 }
3352 return true;
3353 }
3354
3355 @Override
3356 public String getAlwaysOnVpnPackage(int userId) {
3357 enforceConnectivityInternalPermission();
3358 enforceCrossUserPermission(userId);
3359
3360 synchronized (mVpns) {
3361 Vpn vpn = mVpns.get(userId);
3362 if (vpn == null) {
3363 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3364 return null;
3365 }
3366 return vpn.getAlwaysOnPackage();
3367 }
3368 }
3369
Wink Savilleab9321d2013-06-29 21:10:57 -07003370 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003371 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003372 // TODO: Remove? Any reason to trigger a provisioning check?
3373 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003374 }
3375
3376 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003377 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003378
Paul Jensen89e0f092014-09-15 15:59:36 -04003379 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003380 Intent intent = new Intent(action);
3381 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003382 // Concatenate the range of types onto the range of NetIDs.
3383 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003384 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003385 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003386 }
3387
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003388 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003389 * Show or hide network provisioning notifications.
3390 *
3391 * We use notifications for two purposes: to notify that a network requires sign in
3392 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3393 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3394 * particular network we can display the notification type that was most recently requested.
3395 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3396 * might first display NO_INTERNET, and then when the captive portal check completes, display
3397 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003398 *
3399 * @param id an identifier that uniquely identifies this notification. This must match
3400 * between show and hide calls. We use the NetID value but for legacy callers
3401 * we concatenate the range of types with the range of NetIDs.
3402 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003403 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003404 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3405 boolean highPriority) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003406 if (VDBG || (DBG && visible)) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003407 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3408 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003409 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003410 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003411
3412 Resources r = Resources.getSystem();
3413 NotificationManager notificationManager = (NotificationManager) mContext
3414 .getSystemService(Context.NOTIFICATION_SERVICE);
3415
3416 if (visible) {
3417 CharSequence title;
3418 CharSequence details;
3419 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003420 if (notifyType == NotificationType.NO_INTERNET &&
3421 networkType == ConnectivityManager.TYPE_WIFI) {
3422 title = r.getString(R.string.wifi_no_internet, 0);
3423 details = r.getString(R.string.wifi_no_internet_detailed);
3424 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3425 } else if (notifyType == NotificationType.SIGN_IN) {
3426 switch (networkType) {
3427 case ConnectivityManager.TYPE_WIFI:
3428 title = r.getString(R.string.wifi_available_sign_in, 0);
3429 details = r.getString(R.string.network_available_sign_in_detailed,
3430 extraInfo);
3431 icon = R.drawable.stat_notify_wifi_in_range;
3432 break;
3433 case ConnectivityManager.TYPE_MOBILE:
3434 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3435 title = r.getString(R.string.network_available_sign_in, 0);
3436 // TODO: Change this to pull from NetworkInfo once a printable
3437 // name has been added to it
3438 details = mTelephonyManager.getNetworkOperatorName();
3439 icon = R.drawable.stat_notify_rssi_in_range;
3440 break;
3441 default:
3442 title = r.getString(R.string.network_available_sign_in, 0);
3443 details = r.getString(R.string.network_available_sign_in_detailed,
3444 extraInfo);
3445 icon = R.drawable.stat_notify_rssi_in_range;
3446 break;
3447 }
3448 } else {
3449 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3450 + getNetworkTypeName(networkType));
3451 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003452 }
3453
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003454 Notification notification = new Notification.Builder(mContext)
3455 .setWhen(0)
3456 .setSmallIcon(icon)
3457 .setAutoCancel(true)
3458 .setTicker(title)
3459 .setColor(mContext.getColor(
3460 com.android.internal.R.color.system_notification_accent_color))
3461 .setContentTitle(title)
3462 .setContentText(details)
3463 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003464 .setLocalOnly(true)
3465 .setPriority(highPriority ?
3466 Notification.PRIORITY_HIGH :
3467 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003468 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003469 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003470 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003471
Wink Saville948282b2013-08-29 08:55:16 -07003472 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003473 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003474 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003475 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003476 npe.printStackTrace();
3477 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003478 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003479 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003480 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003481 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003482 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003483 npe.printStackTrace();
3484 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003485 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003486 }
3487
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003488 /** Location to an updatable file listing carrier provisioning urls.
3489 * An example:
3490 *
3491 * <?xml version="1.0" encoding="utf-8"?>
3492 * <provisioningUrls>
3493 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003494 * </provisioningUrls>
3495 */
3496 private static final String PROVISIONING_URL_PATH =
3497 "/data/misc/radio/provisioning_urls.xml";
3498 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003499
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003500 /** XML tag for root element. */
3501 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3502 /** XML tag for individual url */
3503 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003504 /** XML attribute for mcc */
3505 private static final String ATTR_MCC = "mcc";
3506 /** XML attribute for mnc */
3507 private static final String ATTR_MNC = "mnc";
3508
Paul Jensen434dde82015-06-11 09:43:30 -04003509 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003510 FileReader fileReader = null;
3511 XmlPullParser parser = null;
3512 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003513
3514 try {
3515 fileReader = new FileReader(mProvisioningUrlFile);
3516 parser = Xml.newPullParser();
3517 parser.setInput(fileReader);
3518 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3519
3520 while (true) {
3521 XmlUtils.nextElement(parser);
3522
3523 String element = parser.getName();
3524 if (element == null) break;
3525
Paul Jensen434dde82015-06-11 09:43:30 -04003526 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003527 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3528 try {
3529 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3530 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3531 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3532 parser.next();
3533 if (parser.getEventType() == XmlPullParser.TEXT) {
3534 return parser.getText();
3535 }
3536 }
3537 }
3538 } catch (NumberFormatException e) {
3539 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3540 }
3541 }
3542 }
3543 return null;
3544 } catch (FileNotFoundException e) {
3545 loge("Carrier Provisioning Urls file not found");
3546 } catch (XmlPullParserException e) {
3547 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3548 } catch (IOException e) {
3549 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3550 } finally {
3551 if (fileReader != null) {
3552 try {
3553 fileReader.close();
3554 } catch (IOException e) {}
3555 }
3556 }
3557 return null;
3558 }
3559
Wink Saville42d4f082013-07-20 20:31:59 -07003560 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003561 public String getMobileProvisioningUrl() {
3562 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003563 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003564 if (TextUtils.isEmpty(url)) {
3565 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003566 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003567 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003568 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003569 }
Wink Saville8cf35602013-07-10 23:00:07 -07003570 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003571 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003572 String phoneNumber = mTelephonyManager.getLine1Number();
3573 if (TextUtils.isEmpty(phoneNumber)) {
3574 phoneNumber = "0000000000";
3575 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003576 url = String.format(url,
3577 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3578 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003579 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003580 }
3581
Wink Savilleab9321d2013-06-29 21:10:57 -07003582 return url;
3583 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003584
Wink Saville948282b2013-08-29 08:55:16 -07003585 @Override
3586 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003587 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003588 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003589 final long ident = Binder.clearCallingIdentity();
3590 try {
3591 setProvNotificationVisible(visible, networkType, action);
3592 } finally {
3593 Binder.restoreCallingIdentity(ident);
3594 }
Wink Saville948282b2013-08-29 08:55:16 -07003595 }
Wink Saville7788c612013-08-29 14:57:08 -07003596
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003597 @Override
3598 public void setAirplaneMode(boolean enable) {
3599 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003600 final long ident = Binder.clearCallingIdentity();
3601 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003602 final ContentResolver cr = mContext.getContentResolver();
3603 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3604 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3605 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003606 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003607 } finally {
3608 Binder.restoreCallingIdentity(ident);
3609 }
3610 }
3611
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003612 private void onUserStart(int userId) {
3613 synchronized(mVpns) {
3614 Vpn userVpn = mVpns.get(userId);
3615 if (userVpn != null) {
3616 loge("Starting user already has a VPN");
3617 return;
3618 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003619 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003620 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003621 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003622 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3623 updateLockdownVpn();
3624 } else {
3625 updateAlwaysOnVpn(userId);
3626 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003627 }
3628
3629 private void onUserStop(int userId) {
3630 synchronized(mVpns) {
3631 Vpn userVpn = mVpns.get(userId);
3632 if (userVpn == null) {
3633 loge("Stopping user has no VPN");
3634 return;
3635 }
3636 mVpns.delete(userId);
3637 }
3638 }
3639
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003640 private void onUserAdded(int userId) {
3641 synchronized(mVpns) {
3642 final int vpnsSize = mVpns.size();
3643 for (int i = 0; i < vpnsSize; i++) {
3644 Vpn vpn = mVpns.valueAt(i);
3645 vpn.onUserAdded(userId);
3646 }
3647 }
3648 }
3649
3650 private void onUserRemoved(int userId) {
3651 synchronized(mVpns) {
3652 final int vpnsSize = mVpns.size();
3653 for (int i = 0; i < vpnsSize; i++) {
3654 Vpn vpn = mVpns.valueAt(i);
3655 vpn.onUserRemoved(userId);
3656 }
3657 }
3658 }
3659
Robin Lee89e7a692016-02-29 14:38:17 +00003660 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003661 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3662 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3663 updateLockdownVpn();
3664 } else {
3665 updateAlwaysOnVpn(userId);
3666 }
3667 }
3668
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003669 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3670 @Override
3671 public void onReceive(Context context, Intent intent) {
3672 final String action = intent.getAction();
3673 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3674 if (userId == UserHandle.USER_NULL) return;
3675
3676 if (Intent.ACTION_USER_STARTING.equals(action)) {
3677 onUserStart(userId);
3678 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3679 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003680 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3681 onUserAdded(userId);
3682 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3683 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003684 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3685 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003686 }
3687 }
3688 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003689
Robert Greenwalta67be032014-05-16 15:49:14 -07003690 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3691 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003692 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3693 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003694
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003695 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3696 // Map from UID to number of NetworkRequests that UID has filed.
3697 @GuardedBy("mUidToNetworkRequestCount")
3698 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3699
Robert Greenwalta67be032014-05-16 15:49:14 -07003700 private static class NetworkFactoryInfo {
3701 public final String name;
3702 public final Messenger messenger;
3703 public final AsyncChannel asyncChannel;
3704
3705 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3706 this.name = name;
3707 this.messenger = messenger;
3708 this.asyncChannel = asyncChannel;
3709 }
3710 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003711
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003712 /**
Erik Kline371c7b72016-03-22 17:04:20 +09003713 * A NetworkRequest as registered by an application can be one of three
3714 * types:
3715 *
3716 * - "listen", for which the framework will issue callbacks about any
3717 * and all networks that match the specified NetworkCapabilities,
3718 *
3719 * - "request", capable of causing a specific network to be created
3720 * first (e.g. a telephony DUN request), the framework will issue
3721 * callbacks about the single, highest scoring current network
3722 * (if any) that matches the specified NetworkCapabilities, or
3723 *
3724 * - "track the default network", a hybrid of the two designed such
3725 * that the framework will issue callbacks for the single, highest
3726 * scoring current network (if any) that matches the capabilities of
3727 * the default Internet request (mDefaultRequest), but which cannot
3728 * cause the framework to either create or retain the existence of
3729 * any specific network.
3730 *
3731 */
3732 private static enum NetworkRequestType {
3733 LISTEN,
3734 TRACK_DEFAULT,
3735 REQUEST
3736 };
3737
3738 /**
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003739 * Tracks info about the requester.
3740 * Also used to notice when the calling process dies so we can self-expire
3741 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003742 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003743 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003744 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003745 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003746 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003747 final int mPid;
3748 final int mUid;
3749 final Messenger messenger;
Erik Kline371c7b72016-03-22 17:04:20 +09003750 private final NetworkRequestType mType;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003751
Erik Kline371c7b72016-03-22 17:04:20 +09003752 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003753 request = r;
3754 mPendingIntent = pi;
3755 messenger = null;
3756 mBinder = null;
3757 mPid = getCallingPid();
3758 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003759 mType = type;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003760 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003761 }
3762
Erik Kline371c7b72016-03-22 17:04:20 +09003763 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003764 super();
3765 messenger = m;
3766 request = r;
3767 mBinder = binder;
3768 mPid = getCallingPid();
3769 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003770 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003771 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003772 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003773
3774 try {
3775 mBinder.linkToDeath(this, 0);
3776 } catch (RemoteException e) {
3777 binderDied();
3778 }
3779 }
3780
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003781 private void enforceRequestCountLimit() {
3782 synchronized (mUidToNetworkRequestCount) {
3783 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3784 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3785 throw new IllegalArgumentException("Too many NetworkRequests filed");
3786 }
3787 mUidToNetworkRequestCount.put(mUid, networkRequests);
3788 }
3789 }
3790
Erik Kline371c7b72016-03-22 17:04:20 +09003791 private String typeString() {
3792 switch (mType) {
3793 case LISTEN: return "Listen";
3794 case REQUEST: return "Request";
3795 case TRACK_DEFAULT: return "Track default";
3796 default:
3797 return "unknown type";
3798 }
3799 }
3800
Robert Greenwalt9258c642014-03-26 16:47:06 -07003801 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003802 if (mBinder != null) {
3803 mBinder.unlinkToDeath(this, 0);
3804 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003805 }
3806
3807 public void binderDied() {
3808 log("ConnectivityService NetworkRequestInfo binderDied(" +
3809 request + ", " + mBinder + ")");
3810 releaseNetworkRequest(request);
3811 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003812
Erik Kline371c7b72016-03-22 17:04:20 +09003813 /**
3814 * Returns true iff. the contained NetworkRequest is one that:
3815 *
3816 * - should be associated with at most one satisfying network
3817 * at a time;
3818 *
3819 * - should cause a network to be kept up if it is the only network
3820 * which can satisfy the NetworkReqeust.
3821 *
3822 * For full detail of how isRequest() is used for pairing Networks with
3823 * NetworkRequests read rematchNetworkAndRequests().
3824 *
3825 * TODO: Rename to something more properly descriptive.
3826 */
3827 public boolean isRequest() {
3828 return (mType == NetworkRequestType.TRACK_DEFAULT) ||
3829 (mType == NetworkRequestType.REQUEST);
3830 }
3831
Robert Greenwalta67be032014-05-16 15:49:14 -07003832 public String toString() {
Erik Kline371c7b72016-03-22 17:04:20 +09003833 return typeString() +
Erik Kline7523eb32015-07-09 18:24:03 +09003834 " from uid/pid:" + mUid + "/" + mPid +
3835 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003836 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003837 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003838 }
3839
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003840 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3841 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3842 if (badCapability != null) {
3843 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003844 }
3845 }
3846
Erik Kline9d598e12015-07-13 16:37:51 +09003847 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003848 final SortedSet<Integer> thresholds = new TreeSet();
3849 synchronized (nai) {
3850 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3851 if (nri.request.networkCapabilities.hasSignalStrength() &&
3852 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3853 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3854 }
3855 }
3856 }
Erik Kline9d598e12015-07-13 16:37:51 +09003857 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003858 }
3859
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003860 private void updateSignalStrengthThresholds(
3861 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3862 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003863 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003864 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3865
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003866 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003867 String detail;
3868 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3869 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3870 } else {
3871 detail = reason;
3872 }
3873 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3874 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3875 }
3876
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003877 nai.asyncChannel.sendMessage(
3878 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003879 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003880 }
3881
Robert Greenwalt9258c642014-03-26 16:47:06 -07003882 @Override
3883 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003884 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Erik Kline371c7b72016-03-22 17:04:20 +09003885 final NetworkRequestType type = (networkCapabilities == null)
3886 ? NetworkRequestType.TRACK_DEFAULT
3887 : NetworkRequestType.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09003888 // If the requested networkCapabilities is null, take them instead from
3889 // the default network request. This allows callers to keep track of
3890 // the system default network.
Erik Kline371c7b72016-03-22 17:04:20 +09003891 if (type == NetworkRequestType.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09003892 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3893 enforceAccessPermission();
3894 } else {
3895 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3896 enforceNetworkRequestPermissions(networkCapabilities);
3897 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003898 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003899 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003900
Robert Greenwalt6078b502014-06-11 16:05:07 -07003901 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003902 throw new IllegalArgumentException("Bad timeout specified");
3903 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003904
Etan Cohenddb9ef02015-11-18 10:56:15 -08003905 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
3906 .equals(networkCapabilities.getNetworkSpecifier())) {
3907 throw new IllegalArgumentException("Invalid network specifier - must not be '"
3908 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
3909 }
3910
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003911 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3912 nextNetworkRequestId());
Erik Kline371c7b72016-03-22 17:04:20 +09003913 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type);
Erik Kline7523eb32015-07-09 18:24:03 +09003914 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003915
3916 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003917 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003918 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003919 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003920 }
3921 return networkRequest;
3922 }
3923
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003924 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003925 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003926 enforceConnectivityInternalPermission();
3927 } else {
3928 enforceChangePermission();
3929 }
3930 }
3931
fenglub15e72b2015-03-20 11:29:56 -07003932 @Override
fengludb571472015-04-21 17:12:05 -07003933 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003934 enforceAccessPermission();
3935 NetworkAgentInfo nai = null;
3936 if (network == null) {
3937 return false;
3938 }
3939 synchronized (mNetworkForNetId) {
3940 nai = mNetworkForNetId.get(network.netId);
3941 }
3942 if (nai != null) {
3943 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3944 return true;
3945 }
3946 return false;
3947 }
3948
3949
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003950 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3951 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003952 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003953 final int uidRules;
3954 final int uid = Binder.getCallingUid();
3955 synchronized(mRulesLock) {
3956 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3957 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003958 if (uidRules != RULE_ALLOW_ALL) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003959 // we could silently fail or we can filter the available nets to only give
3960 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003961 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003962 }
3963 }
3964 }
3965
Robert Greenwalt9258c642014-03-26 16:47:06 -07003966 @Override
3967 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3968 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003969 checkNotNull(operation, "PendingIntent cannot be null.");
3970 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3971 enforceNetworkRequestPermissions(networkCapabilities);
3972 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003973 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003974
3975 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3976 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003977 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09003978 NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003979 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003980 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3981 nri));
3982 return networkRequest;
3983 }
3984
Jeremy Joslin79294842014-12-03 17:15:28 -08003985 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3986 mHandler.sendMessageDelayed(
3987 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3988 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3989 }
3990
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003991 @Override
3992 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003993 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003994 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3995 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003996 }
3997
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003998 // In order to implement the compatibility measure for pre-M apps that call
3999 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4000 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4001 // This ensures it has permission to do so.
4002 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4003 if (nc == null) {
4004 return false;
4005 }
4006 int[] transportTypes = nc.getTransportTypes();
4007 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4008 return false;
4009 }
4010 try {
4011 mContext.enforceCallingOrSelfPermission(
4012 android.Manifest.permission.ACCESS_WIFI_STATE,
4013 "ConnectivityService");
4014 } catch (SecurityException e) {
4015 return false;
4016 }
4017 return true;
4018 }
4019
Robert Greenwalt9258c642014-03-26 16:47:06 -07004020 @Override
4021 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4022 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004023 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4024 enforceAccessPermission();
4025 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004026
Erik Kline7523eb32015-07-09 18:24:03 +09004027 NetworkRequest networkRequest = new NetworkRequest(
4028 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004029 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
Erik Kline371c7b72016-03-22 17:04:20 +09004030 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004031 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004032
4033 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4034 return networkRequest;
4035 }
4036
4037 @Override
4038 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4039 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004040 checkNotNull(operation, "PendingIntent cannot be null.");
4041 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4042 enforceAccessPermission();
4043 }
4044
Erik Kline7523eb32015-07-09 18:24:03 +09004045 NetworkRequest networkRequest = new NetworkRequest(
4046 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04004047 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004048 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004049 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004050
4051 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004052 }
4053
4054 @Override
4055 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04004056 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4057 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004058 }
4059
4060 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004061 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004062 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004063 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4064 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004065 }
4066
Robert Greenwalta67be032014-05-16 15:49:14 -07004067 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004068 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004069 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4070 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4071 }
4072
4073 @Override
4074 public void unregisterNetworkFactory(Messenger messenger) {
4075 enforceConnectivityInternalPermission();
4076 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4077 }
4078
4079 private void handleUnregisterNetworkFactory(Messenger messenger) {
4080 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4081 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004082 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004083 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004084 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004085 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004086 }
4087
Robert Greenwalt7b816022014-04-18 15:25:25 -07004088 /**
4089 * NetworkAgentInfo supporting a request by requestId.
4090 * These have already been vetted (their Capabilities satisfy the request)
4091 * and the are the highest scored network available.
4092 * the are keyed off the Requests requestId.
4093 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004094 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004095 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4096 new SparseArray<NetworkAgentInfo>();
4097
Paul Jensen31a94f42015-02-13 14:18:39 -05004098 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4099 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004100 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4101 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004102 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4103 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4104 // there may not be a strict 1:1 correlation between the two.
4105 @GuardedBy("mNetworkForNetId")
4106 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004107
Robert Greenwalt7b816022014-04-18 15:25:25 -07004108 // NetworkAgentInfo keyed off its connecting messenger
4109 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004110 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004111 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4112 new HashMap<Messenger, NetworkAgentInfo>();
4113
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004114 @GuardedBy("mBlockedAppUids")
4115 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4116
Paul Jensen2c311d62014-11-17 12:34:51 -05004117 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004118 private final NetworkRequest mDefaultRequest;
4119
Erik Klineda4bfa82015-04-30 12:58:40 +09004120 // Request used to optionally keep mobile data active even when higher
4121 // priority networks like Wi-Fi are active.
4122 private final NetworkRequest mDefaultMobileDataRequest;
4123
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004124 private NetworkAgentInfo getDefaultNetwork() {
4125 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4126 }
4127
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004128 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004129 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004130 }
4131
Paul Jensen31a94f42015-02-13 14:18:39 -05004132 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004133 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004134 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004135 enforceConnectivityInternalPermission();
4136
Paul Jensen2c311d62014-11-17 12:34:51 -05004137 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4138 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004139 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004140 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4141 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004142 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004143 synchronized (this) {
4144 nai.networkMonitor.systemReady = mSystemReady;
4145 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07004146 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004147 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004148 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004149 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004150 }
4151
4152 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4153 if (VDBG) log("Got NetworkAgent Messenger");
4154 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004155 synchronized (mNetworkForNetId) {
4156 mNetworkForNetId.put(na.network.netId, na);
4157 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004158 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4159 NetworkInfo networkInfo = na.networkInfo;
4160 na.networkInfo = null;
4161 updateNetworkInfo(na, networkInfo);
4162 }
4163
4164 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4165 LinkProperties newLp = networkAgent.linkProperties;
4166 int netId = networkAgent.network.netId;
4167
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004168 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4169 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004170 if (networkAgent.clatd != null) {
4171 networkAgent.clatd.fixupLinkProperties(oldLp);
4172 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004173
Paul Jensen992f2522014-04-28 10:33:11 -04004174 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004175 updateMtu(newLp, oldLp);
4176 // TODO - figure out what to do for clat
4177// for (LinkProperties lp : newLp.getStackedLinks()) {
4178// updateMtu(lp, null);
4179// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004180 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004181
Erik Kline94887872016-04-05 13:30:49 +09004182 updateRoutes(newLp, oldLp, netId);
4183 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004184
Paul Jensen3b759822014-05-13 11:44:01 -04004185 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004186 if (isDefaultNetwork(networkAgent)) {
4187 handleApplyDefaultProxy(newLp.getHttpProxy());
4188 } else {
4189 updateProxy(newLp, oldLp, networkAgent);
4190 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004191 // TODO - move this check to cover the whole function
4192 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004193 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004194 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4195 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004196
4197 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004198 }
4199
Lorenzo Colitti95439462014-10-09 13:44:48 +09004200 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4201 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4202 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004203
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004204 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004205 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4206 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004207 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004208 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004209 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004210 }
Paul Jensen992f2522014-04-28 10:33:11 -04004211
4212 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4213 CompareResult<String> interfaceDiff = new CompareResult<String>();
4214 if (oldLp != null) {
4215 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4216 } else if (newLp != null) {
4217 interfaceDiff.added = newLp.getAllInterfaceNames();
4218 }
4219 for (String iface : interfaceDiff.added) {
4220 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004221 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004222 mNetd.addInterfaceToNetwork(iface, netId);
4223 } catch (Exception e) {
4224 loge("Exception adding interface: " + e);
4225 }
4226 }
4227 for (String iface : interfaceDiff.removed) {
4228 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004229 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004230 mNetd.removeInterfaceFromNetwork(iface, netId);
4231 } catch (Exception e) {
4232 loge("Exception removing interface: " + e);
4233 }
4234 }
4235 }
4236
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004237 /**
4238 * Have netd update routes from oldLp to newLp.
4239 * @return true if routes changed between oldLp and newLp
4240 */
4241 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004242 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4243 if (oldLp != null) {
4244 routeDiff = oldLp.compareAllRoutes(newLp);
4245 } else if (newLp != null) {
4246 routeDiff.added = newLp.getAllRoutes();
4247 }
4248
4249 // add routes before removing old in case it helps with continuous connectivity
4250
4251 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4252 for (RouteInfo route : routeDiff.added) {
4253 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004254 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004255 try {
4256 mNetd.addRoute(netId, route);
4257 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004258 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4259 loge("Exception in addRoute for non-gateway: " + e);
4260 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004261 }
4262 }
4263 for (RouteInfo route : routeDiff.added) {
4264 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004265 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004266 try {
4267 mNetd.addRoute(netId, route);
4268 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004269 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4270 loge("Exception in addRoute for gateway: " + e);
4271 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004272 }
4273 }
4274
4275 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004276 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004277 try {
4278 mNetd.removeRoute(netId, route);
4279 } catch (Exception e) {
4280 loge("Exception in removeRoute: " + e);
4281 }
4282 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004283 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004284 }
Erik Kline41368502015-06-17 13:19:54 +09004285
Erik Kline94887872016-04-05 13:30:49 +09004286 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4287 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4288 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004289 }
Erik Kline94887872016-04-05 13:30:49 +09004290
4291 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004292 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004293 try {
4294 mNetd.setDnsServersForNetwork(
4295 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4296 } catch (Exception e) {
4297 loge("Exception in setDnsServersForNetwork: " + e);
4298 }
4299 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4300 if (defaultNai != null && defaultNai.network.netId == netId) {
4301 setDefaultDnsSystemProperties(dnses);
4302 }
4303 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004304 }
4305
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004306 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4307 int last = 0;
4308 for (InetAddress dns : dnses) {
4309 ++last;
4310 String key = "net.dns" + last;
4311 String value = dns.getHostAddress();
4312 SystemProperties.set(key, value);
4313 }
4314 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4315 String key = "net.dns" + i;
4316 SystemProperties.set(key, "");
4317 }
4318 mNumDnsEntries = last;
4319 }
4320
Paul Jensen3d194ea2015-06-16 14:27:36 -04004321 /**
4322 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4323 * augmented with any stateful capabilities implied from {@code networkAgent}
4324 * (e.g., validated status and captive portal status).
4325 *
Paul Jensene0988542015-06-25 15:30:08 -04004326 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004327 * @param networkCapabilities the new network capabilities.
4328 */
Paul Jensene0988542015-06-25 15:30:08 -04004329 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004330 // Don't modify caller's NetworkCapabilities.
4331 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004332 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004333 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4334 } else {
4335 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4336 }
Paul Jensene0988542015-06-25 15:30:08 -04004337 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004338 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4339 } else {
4340 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4341 }
Paul Jensene0988542015-06-25 15:30:08 -04004342 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4343 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004344 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4345 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4346 try {
4347 mNetd.setNetworkPermission(nai.network.netId,
4348 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4349 null : NetworkManagementService.PERMISSION_SYSTEM);
4350 } catch (RemoteException e) {
4351 loge("Exception in setNetworkPermission: " + e);
4352 }
4353 }
Paul Jensene0988542015-06-25 15:30:08 -04004354 synchronized (nai) {
4355 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004356 }
Paul Jensene0988542015-06-25 15:30:08 -04004357 rematchAllNetworksAndRequests(nai, oldScore);
4358 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004359 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004360 }
4361
Paul Jensenc8b9a742014-09-30 15:37:41 -04004362 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4363 for (int i = 0; i < nai.networkRequests.size(); i++) {
4364 NetworkRequest nr = nai.networkRequests.valueAt(i);
4365 // Don't send listening requests to factories. b/17393458
4366 if (!isRequest(nr)) continue;
4367 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4368 }
4369 }
4370
Robert Greenwalt7b816022014-04-18 15:25:25 -07004371 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4372 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004373 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004374 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4375 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004376 }
4377 }
4378
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004379 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4380 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004381 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004382 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004383 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4384 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004385 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004386 sendIntent(nri.mPendingIntent, intent);
4387 }
4388 // else not handled
4389 }
4390
4391 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4392 mPendingIntentWakeLock.acquire();
4393 try {
4394 if (DBG) log("Sending " + pendingIntent);
4395 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4396 } catch (PendingIntent.CanceledException e) {
4397 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4398 mPendingIntentWakeLock.release();
4399 releasePendingNetworkRequest(pendingIntent);
4400 }
4401 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4402 }
4403
4404 @Override
4405 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4406 String resultData, Bundle resultExtras) {
4407 if (DBG) log("Finished sending " + pendingIntent);
4408 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004409 // Release with a delay so the receiving client has an opportunity to put in its
4410 // own request.
4411 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004412 }
4413
Robert Greenwalt9258c642014-03-26 16:47:06 -07004414 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004415 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004416 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004417 Bundle bundle = new Bundle();
4418 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4419 new NetworkRequest(nri.request));
4420 Message msg = Message.obtain();
4421 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4422 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4423 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4424 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004425 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004426 case ConnectivityManager.CALLBACK_LOSING: {
4427 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4428 break;
4429 }
4430 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4431 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4432 new NetworkCapabilities(networkAgent.networkCapabilities));
4433 break;
4434 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004435 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004436 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4437 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004438 break;
4439 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004440 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004441 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004442 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004443 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004444 if (VDBG) {
4445 log("sending notification " + notifyTypeToName(notificationType) +
4446 " for " + nri.request);
4447 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004448 nri.messenger.send(msg);
4449 } catch (RemoteException e) {
4450 // may occur naturally in the race of binder death.
4451 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4452 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004453 }
4454
Paul Jensenc8b9a742014-09-30 15:37:41 -04004455 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4456 for (int i = 0; i < nai.networkRequests.size(); i++) {
4457 NetworkRequest nr = nai.networkRequests.valueAt(i);
4458 // Ignore listening requests.
4459 if (!isRequest(nr)) continue;
4460 loge("Dead network still had at least " + nr);
4461 break;
4462 }
4463 nai.asyncChannel.disconnect();
4464 }
4465
Robert Greenwalt7b816022014-04-18 15:25:25 -07004466 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4467 if (oldNetwork == null) {
4468 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4469 return;
4470 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004471 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4472 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004473 }
4474
Pierre Imai6b4e15b2016-04-07 12:21:05 +09004475 private void makeDefault(NetworkAgentInfo newNetwork, NetworkAgentInfo prevNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004476 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004477 setupDataActivityTracking(newNetwork);
4478 try {
4479 mNetd.setDefaultNetId(newNetwork.network.netId);
4480 } catch (Exception e) {
4481 loge("Exception setting default network :" + e);
4482 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004483 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004484 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004485 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004486 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Hugo Benichi5f16f762016-04-20 12:09:33 +09004487 logDefaultNetworkEvent(newNetwork, prevNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004488 }
4489
Paul Jensen2161a8e2014-09-11 11:00:39 -04004490 // Handles a network appearing or improving its score.
4491 //
4492 // - Evaluates all current NetworkRequests that can be
4493 // satisfied by newNetwork, and reassigns to newNetwork
4494 // any such requests for which newNetwork is the best.
4495 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004496 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004497 // needed. A network is needed if it is the best network for
4498 // one or more NetworkRequests, or if it is a VPN.
4499 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004500 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004501 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004502 //
4503 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4504 // networks that have no chance (i.e. even if validated)
4505 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004506 //
4507 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4508 // it does not remove NetworkRequests that other Networks could better satisfy.
4509 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4510 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4511 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004512 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004513 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004514 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4515 // performed to tear down unvalidated networks that have no chance (i.e. even if
4516 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004517 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004518 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004519 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004520 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004521 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004522 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004523 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004524 // Find and migrate to this Network any NetworkRequests for
4525 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004526 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004527 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004528 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004529 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004530 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4531 final boolean satisfies = newNetwork.satisfies(nri.request);
4532 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004533 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004534 log("Network " + newNetwork.name() + " was already satisfying" +
4535 " request " + nri.request.requestId + ". No change.");
4536 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004537 keep = true;
4538 continue;
4539 }
4540
4541 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004542 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004543 if (satisfies) {
Erik Kline371c7b72016-03-22 17:04:20 +09004544 if (!nri.isRequest()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004545 // This is not a request, it's a callback listener.
4546 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004547 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004548 continue;
4549 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004550
Robert Greenwalt7b816022014-04-18 15:25:25 -07004551 // next check if it's better than any current network we're using for
4552 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004553 if (VDBG) {
4554 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004555 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4556 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004557 }
4558 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004559 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004560 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004561 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004562 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004563 currentNetwork.networkRequests.remove(nri.request.requestId);
4564 currentNetwork.networkLingered.add(nri.request);
4565 affectedNetworks.add(currentNetwork);
4566 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004567 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004568 }
Paul Jensen573a0352015-01-08 10:49:34 -05004569 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004570 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004571 if (!newNetwork.addRequest(nri.request)) {
4572 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4573 }
4574 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004575 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004576 // Tell NetworkFactories about the new score, so they can stop
4577 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004578 // TODO - this could get expensive if we have alot of requests for this
4579 // network. Think about if there is a way to reduce this. Push
4580 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004581 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004582 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004583 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004584 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004585 }
4586 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004587 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4588 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4589 // mark it as no longer satisfying "nri". Because networks are processed by
4590 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4591 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4592 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4593 // This means this code doesn't have to handle the case where "currentNetwork" no
4594 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4595 if (DBG) {
4596 log("Network " + newNetwork.name() + " stopped satisfying" +
4597 " request " + nri.request.requestId);
4598 }
4599 newNetwork.networkRequests.remove(nri.request.requestId);
4600 if (currentNetwork == newNetwork) {
4601 mNetworkForRequestId.remove(nri.request.requestId);
4602 sendUpdatedScoreToFactories(nri.request, 0);
4603 } else {
Erik Kline371c7b72016-03-22 17:04:20 +09004604 if (nri.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004605 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4606 newNetwork.name() +
4607 " without updating mNetworkForRequestId or factories!");
4608 }
4609 }
4610 // TODO: technically, sending CALLBACK_LOST here is
4611 // incorrect if nri is a request (not a listen) and there
4612 // is a replacement network currently connected that can
4613 // satisfy it. However, the only capability that can both
4614 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4615 // so this code is only incorrect for a network that loses
4616 // the TRUSTED capability, which is a rare case.
4617 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004618 }
4619 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004620 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004621 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004622 if (nai.lingering) {
4623 // Already lingered. Nothing to do. This can only happen if "nai" is in
4624 // "affectedNetworks" twice. The reasoning being that to get added to
4625 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4626 // (i.e. not lingered) so it could have only been lingered by this loop.
4627 // unneeded(nai) will be false and we'll call unlinger() below which would
4628 // be bad, so handle it here.
4629 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004630 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004631 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004632 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004633 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004634 }
4635 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004636 if (isNewDefault) {
4637 // Notify system services that this network is up.
Pierre Imai6b4e15b2016-04-07 12:21:05 +09004638 makeDefault(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004639 synchronized (ConnectivityService.this) {
4640 // have a new default network, release the transition wakelock in
4641 // a second if it's held. The second pause is to allow apps
4642 // to reconnect over the new network
4643 if (mNetTransitionWakeLock.isHeld()) {
4644 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4645 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4646 mNetTransitionWakeLockSerialNumber, 0),
4647 1000);
4648 }
4649 }
4650 }
4651
4652 // do this after the default net is switched, but
4653 // before LegacyTypeTracker sends legacy broadcasts
4654 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4655
4656 if (isNewDefault) {
4657 // Maintain the illusion: since the legacy API only
4658 // understands one network at a time, we must pretend
4659 // that the current default network disconnected before
4660 // the new one connected.
4661 if (oldDefaultNetwork != null) {
4662 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4663 oldDefaultNetwork, true);
4664 }
4665 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4666 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4667 notifyLockdownVpn(newNetwork);
4668 }
4669
Robert Greenwalt7b816022014-04-18 15:25:25 -07004670 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004671 // Notify battery stats service about this network, both the normal
4672 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004673 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004674 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004675 final IBatteryStats bs = BatteryStatsService.getService();
4676 final int type = newNetwork.networkInfo.getType();
4677
4678 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4679 bs.noteNetworkInterfaceType(baseIface, type);
4680 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4681 final String stackedIface = stacked.getInterfaceName();
4682 bs.noteNetworkInterfaceType(stackedIface, type);
4683 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4684 }
4685 } catch (RemoteException ignored) {
4686 }
4687
Robert Greenwalt152ed372014-12-17 17:19:53 -08004688 // This has to happen after the notifyNetworkCallbacks as that tickles each
4689 // ConnectivityManager instance so that legacy requests correctly bind dns
4690 // requests to this network. The legacy users are listening for this bcast
4691 // and will generally do a dns request so they can ensureRouteToHost and if
4692 // they do that before the callbacks happen they'll use the default network.
4693 //
4694 // TODO: Is there still a race here? We send the broadcast
4695 // after sending the callback, but if the app can receive the
4696 // broadcast before the callback, it might still break.
4697 //
4698 // This *does* introduce a race where if the user uses the new api
4699 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4700 // they may get old info. Reverse this after the old startUsing api is removed.
4701 // This is on top of the multiple intent sequencing referenced in the todo above.
4702 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4703 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4704 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4705 // legacy type tracker filters out repeat adds
4706 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4707 }
4708 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004709
4710 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4711 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4712 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4713 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4714 if (newNetwork.isVPN()) {
4715 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4716 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004717 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004718 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4719 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004720 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004721 if (DBG) log("Reaping " + nai.name());
4722 teardownUnneededNetwork(nai);
4723 }
4724 }
4725 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004726 }
4727
Paul Jensen1c7ba022015-06-16 14:27:36 -04004728 /**
4729 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4730 * being disconnected.
4731 * @param changed If only one Network's score or capabilities have been modified since the last
4732 * time this function was called, pass this Network in this argument, otherwise pass
4733 * null.
4734 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4735 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4736 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4737 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4738 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004739 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004740 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004741 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4742 // to avoid the slowness. It is not simply enough to process just "changed", for
4743 // example in the case where "changed"'s score decreases and another network should begin
4744 // satifying a NetworkRequest that "changed" currently satisfies.
4745
4746 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4747 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4748 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004749 if (changed != null && oldScore < changed.getCurrentScore()) {
4750 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004751 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004752 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4753 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4754 // Rematch higher scoring networks first to prevent requests first matching a lower
4755 // scoring network and then a higher scoring network, which could produce multiple
4756 // callbacks and inadvertently unlinger networks.
4757 Arrays.sort(nais);
4758 for (NetworkAgentInfo nai : nais) {
4759 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004760 // Only reap the last time through the loop. Reaping before all rematching
4761 // is complete could incorrectly teardown a network that hasn't yet been
4762 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004763 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004764 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004765 }
4766 }
4767 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004768
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004769 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004770 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004771 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004772 // For now only update icons for default connection.
4773 // TODO: Update WiFi and cellular icons separately. b/17237507
4774 if (!isDefaultNetwork(nai)) return;
4775
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004776 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004777 // Don't repeat publish.
4778 if (newInetCondition == mDefaultInetConditionPublished) return;
4779
4780 mDefaultInetConditionPublished = newInetCondition;
4781 sendInetConditionBroadcast(nai.networkInfo);
4782 }
4783
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004784 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4785 if (mLockdownTracker != null) {
4786 if (nai != null && nai.isVPN()) {
4787 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4788 } else {
4789 mLockdownTracker.onNetworkInfoChanged();
4790 }
4791 }
4792 }
4793
Robert Greenwalt7b816022014-04-18 15:25:25 -07004794 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4795 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004796 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004797 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004798 synchronized (networkAgent) {
4799 oldInfo = networkAgent.networkInfo;
4800 networkAgent.networkInfo = newInfo;
4801 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004802 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004803
4804 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004805 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4806 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4807 notifyIfacesChangedForNetworkStats();
4808 } else if (VDBG) log("ignoring duplicate network state non-change");
4809 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004810 return;
4811 }
4812 if (DBG) {
4813 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4814 (oldInfo == null ? "null" : oldInfo.getState()) +
4815 " to " + state);
4816 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004817
Paul Jenseneec75412014-08-04 12:21:19 -04004818 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004819 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004820 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004821 if (networkAgent.isVPN()) {
4822 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004823 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4824 (networkAgent.networkMisc == null ||
4825 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004826 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004827 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4828 networkAgent.networkCapabilities.hasCapability(
4829 NET_CAPABILITY_NOT_RESTRICTED) ?
4830 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004831 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004832 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004833 loge("Error creating network " + networkAgent.network.netId + ": "
4834 + e.getMessage());
4835 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004836 }
Paul Jenseneec75412014-08-04 12:21:19 -04004837 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004838 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004839 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004840
Paul Jensenca8f16a2014-05-09 12:47:55 -04004841 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004842 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004843
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004844 if (networkAgent.isVPN()) {
4845 // Temporarily disable the default proxy (not global).
4846 synchronized (mProxyLock) {
4847 if (!mDefaultProxyDisabled) {
4848 mDefaultProxyDisabled = true;
4849 if (mGlobalProxy == null && mDefaultProxy != null) {
4850 sendProxyBroadcast(null);
4851 }
4852 }
4853 }
4854 // TODO: support proxy per network.
4855 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004856
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004857 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4858 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4859 // capabilities, so it only needs to be done once on initial connect, not every time the
4860 // network's capabilities change. Note that we do this before rematching the network,
4861 // so we could decide to tear it down immediately afterwards. That's fine though - on
4862 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4863 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004864 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004865
Paul Jensen2161a8e2014-09-11 11:00:39 -04004866 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004867 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004868
4869 // This has to happen after matching the requests, because callbacks are just requests.
4870 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004871 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004872 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004873 if (networkAgent.isVPN()) {
4874 synchronized (mProxyLock) {
4875 if (mDefaultProxyDisabled) {
4876 mDefaultProxyDisabled = false;
4877 if (mGlobalProxy == null && mDefaultProxy != null) {
4878 sendProxyBroadcast(mDefaultProxy);
4879 }
4880 }
4881 }
4882 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004883 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4884 state == NetworkInfo.State.SUSPENDED) {
4885 // going into or coming out of SUSPEND: rescore and notify
4886 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004887 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004888 }
4889 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4890 ConnectivityManager.CALLBACK_SUSPENDED :
4891 ConnectivityManager.CALLBACK_RESUMED));
4892 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004893 }
4894 }
4895
Robert Greenwaltac96c522014-06-03 16:43:57 -07004896 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004897 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004898 if (score < 0) {
4899 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4900 "). Bumping score to min of 0");
4901 score = 0;
4902 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004903
Paul Jensen2161a8e2014-09-11 11:00:39 -04004904 final int oldScore = nai.getCurrentScore();
4905 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004906
Paul Jensen85cf78e2015-06-25 13:25:07 -04004907 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004908
Paul Jensenc8b9a742014-09-30 15:37:41 -04004909 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004910 }
4911
Robert Greenwalt9258c642014-03-26 16:47:06 -07004912 // notify only this one new request of the current state
4913 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4914 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4915 // TODO - read state from monitor to decide what to send.
4916// if (nai.networkMonitor.isLingering()) {
4917// notifyType = NetworkCallbacks.LOSING;
4918// } else if (nai.networkMonitor.isEvaluating()) {
4919// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4920// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004921 if (nri.mPendingIntent == null) {
4922 callCallbackForRequest(nri, nai, notifyType);
4923 } else {
4924 sendPendingIntentForRequest(nri, nai, notifyType);
4925 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004926 }
4927
Robert Greenwalt8d482522015-06-24 13:23:42 -07004928 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004929 // The NetworkInfo we actually send out has no bearing on the real
4930 // state of affairs. For example, if the default connection is mobile,
4931 // and a request for HIPRI has just gone away, we need to pretend that
4932 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4933 // the state to DISCONNECTED, even though the network is of type MOBILE
4934 // and is still connected.
4935 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4936 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004937 if (state != DetailedState.DISCONNECTED) {
4938 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004939 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004940 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004941 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004942 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4943 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4944 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4945 if (info.isFailover()) {
4946 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4947 nai.networkInfo.setFailover(false);
4948 }
4949 if (info.getReason() != null) {
4950 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4951 }
4952 if (info.getExtraInfo() != null) {
4953 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4954 }
4955 NetworkAgentInfo newDefaultAgent = null;
4956 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004957 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004958 if (newDefaultAgent != null) {
4959 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4960 newDefaultAgent.networkInfo);
4961 } else {
4962 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4963 }
4964 }
4965 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4966 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004967 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004968 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004969 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004970 }
4971 }
4972 }
4973
Robert Greenwalt7b816022014-04-18 15:25:25 -07004974 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004975 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004976 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004977 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4978 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4979 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004980 if (nri.mPendingIntent == null) {
4981 callCallbackForRequest(nri, networkAgent, notifyType);
4982 } else {
4983 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4984 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004985 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004986 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004987
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004988 private String notifyTypeToName(int notifyType) {
4989 switch (notifyType) {
4990 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4991 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4992 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4993 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4994 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4995 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4996 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4997 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4998 }
4999 return "UNKNOWN";
5000 }
5001
Jeff Sharkey69736342014-12-08 14:50:12 -08005002 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005003 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5004 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005005 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005006 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005007 try {
5008 mStatsService.forceUpdateIfaces();
5009 } catch (Exception ignored) {
5010 }
5011 }
5012
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005013 @Override
5014 public boolean addVpnAddress(String address, int prefixLength) {
5015 throwIfLockdownEnabled();
5016 int user = UserHandle.getUserId(Binder.getCallingUid());
5017 synchronized (mVpns) {
5018 return mVpns.get(user).addAddress(address, prefixLength);
5019 }
5020 }
5021
5022 @Override
5023 public boolean removeVpnAddress(String address, int prefixLength) {
5024 throwIfLockdownEnabled();
5025 int user = UserHandle.getUserId(Binder.getCallingUid());
5026 synchronized (mVpns) {
5027 return mVpns.get(user).removeAddress(address, prefixLength);
5028 }
5029 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005030
5031 @Override
5032 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5033 throwIfLockdownEnabled();
5034 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005035 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005036 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005037 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005038 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005039 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005040 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005041 }
5042 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005043 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005044
5045 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005046 public String getCaptivePortalServerUrl() {
5047 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5048 }
5049
5050 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005051 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5052 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5053 enforceKeepalivePermission();
5054 mKeepaliveTracker.startNattKeepalive(
5055 getNetworkAgentInfoForNetwork(network),
5056 intervalSeconds, messenger, binder,
5057 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5058 }
5059
5060 @Override
5061 public void stopKeepalive(Network network, int slot) {
5062 mHandler.sendMessage(mHandler.obtainMessage(
5063 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5064 }
5065
5066 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005067 public void factoryReset() {
5068 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005069
5070 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5071 return;
5072 }
5073
Robin Lee3b3dd942015-05-12 18:14:58 +01005074 final int userId = UserHandle.getCallingUserId();
5075
Stuart Scottf1fb3972015-04-02 18:00:02 -07005076 // Turn airplane mode off
5077 setAirplaneMode(false);
5078
Stuart Scotte3e314d2015-04-20 14:07:45 -07005079 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5080 // Untether
5081 for (String tether : getTetheredIfaces()) {
5082 untether(tether);
5083 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005084 }
5085
Stuart Scotte3e314d2015-04-20 14:07:45 -07005086 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
5087 // Turn VPN off
5088 VpnConfig vpnConfig = getVpnConfig(userId);
5089 if (vpnConfig != null) {
5090 if (vpnConfig.legacy) {
5091 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5092 } else {
5093 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5094 // in the future without user intervention.
5095 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005096
Stuart Scotte3e314d2015-04-20 14:07:45 -07005097 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
5098 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005099 }
5100 }
5101 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005102
5103 @VisibleForTesting
5104 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5105 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5106 return new NetworkMonitor(context, handler, nai, defaultRequest);
5107 }
Erik Kline48f12f22016-04-14 17:30:59 +09005108
Hugo Benichi5f16f762016-04-20 12:09:33 +09005109 private static void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
5110 int newNetid = NETID_UNSET;
5111 int prevNetid = NETID_UNSET;
5112 int[] transports = new int[0];
5113 boolean hadIPv4 = false;
5114 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005115
Hugo Benichi5f16f762016-04-20 12:09:33 +09005116 if (newNai != null) {
5117 newNetid = newNai.network.netId;
5118 transports = newNai.networkCapabilities.getTransportTypes();
5119 }
5120 if (prevNai != null) {
5121 prevNetid = prevNai.network.netId;
5122 final LinkProperties lp = prevNai.linkProperties;
5123 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5124 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5125 }
5126
5127 DefaultNetworkEvent.logEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6);
Erik Kline48f12f22016-04-14 17:30:59 +09005128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005129}