blob: 75643f6a626908c0bb52b92eae991d92612c4e88 [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) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800824 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600825 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
826 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800827 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600828 state = nai.getNetworkState();
829 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800830 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600831 final NetworkInfo info = new NetworkInfo(networkType, 0,
832 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800833 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
834 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600835 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
836 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800837 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600838 filterNetworkStateForUid(state, uid);
839 return state;
840 } else {
841 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800842 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400843 }
844
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800845 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
846 if (network == null) {
847 return null;
848 }
849 synchronized (mNetworkForNetId) {
850 return mNetworkForNetId.get(network.netId);
851 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600852 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800853
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900854 private Network[] getVpnUnderlyingNetworks(int uid) {
855 if (!mLockdownEnabled) {
856 int user = UserHandle.getUserId(uid);
857 synchronized (mVpns) {
858 Vpn vpn = mVpns.get(user);
859 if (vpn != null && vpn.appliesToUid(uid)) {
860 return vpn.getUnderlyingNetworks();
861 }
862 }
863 }
864 return null;
865 }
866
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800867 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400868 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800869
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900870 final Network[] networks = getVpnUnderlyingNetworks(uid);
871 if (networks != null) {
872 // getUnderlyingNetworks() returns:
873 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
874 // empty array => the VPN explicitly said "no default network".
875 // non-empty array => the VPN specified one or more default networks; we use the
876 // first one.
877 if (networks.length > 0) {
878 nai = getNetworkAgentInfoForNetwork(networks[0]);
879 } else {
880 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800881 }
882 }
883
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800884 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600885 return nai.getNetworkState();
886 } else {
887 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800888 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400889 }
890
891 /**
892 * Check if UID should be blocked from using the network with the given LinkProperties.
893 */
894 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700895 final boolean networkCostly;
896 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700897
Robert Greenwalt12e67352014-05-13 21:41:06 -0700898 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700899 synchronized (mRulesLock) {
900 networkCostly = mMeteredIfaces.contains(iface);
901 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700902 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700903
Jeff Sharkeydc988062015-09-14 10:09:47 -0700904 if (uidRules == RULE_REJECT_ALL) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700905 return true;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700906 } else if ((uidRules == RULE_REJECT_METERED) && networkCostly) {
907 return true;
908 } else {
909 return false;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700910 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700911 }
912
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900913 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
914 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
915 boolean removed = false;
916 boolean added = false;
917 synchronized (mBlockedAppUids) {
918 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
919 added = true;
920 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
921 removed = true;
922 }
923 }
924 if (added) log("Returning blocked NetworkInfo to uid=" + uid);
925 else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
926 }
927
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700928 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600929 * Apply any relevant filters to {@link NetworkState} for the given UID. For
930 * example, this may mark the network as {@link DetailedState#BLOCKED} based
931 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
932 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700933 */
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600934 private void filterNetworkStateForUid(NetworkState state, int uid) {
935 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
936
937 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
938 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700939 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600940 if (mLockdownTracker != null) {
941 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700942 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600943
944 // TODO: apply metered state closer to NetworkAgentInfo
945 final long token = Binder.clearCallingIdentity();
946 try {
947 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
948 } catch (RemoteException e) {
949 } finally {
950 Binder.restoreCallingIdentity(token);
951 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700952 }
953
954 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 * Return NetworkInfo for the active (i.e., connected) network interface.
956 * It is assumed that at most one network is active at a time. If more
957 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700958 * @return the info for the active network, or {@code null} if none is
959 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700961 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700963 enforceAccessPermission();
964 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600965 final NetworkState state = getUnfilteredActiveNetworkState(uid);
966 filterNetworkStateForUid(state, uid);
967 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
968 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 }
970
Paul Jensen31a94f42015-02-13 14:18:39 -0500971 @Override
972 public Network getActiveNetwork() {
973 enforceAccessPermission();
Robin Leed2baf792016-03-24 12:07:00 +0000974 return getActiveNetworkForUidInternal(Binder.getCallingUid());
975 }
976
977 @Override
978 public Network getActiveNetworkForUid(int uid) {
979 enforceConnectivityInternalPermission();
980 return getActiveNetworkForUidInternal(uid);
981 }
982
983 private Network getActiveNetworkForUidInternal(final int uid) {
Paul Jensen31a94f42015-02-13 14:18:39 -0500984 final int user = UserHandle.getUserId(uid);
985 int vpnNetId = NETID_UNSET;
986 synchronized (mVpns) {
987 final Vpn vpn = mVpns.get(user);
988 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
989 }
990 NetworkAgentInfo nai;
991 if (vpnNetId != NETID_UNSET) {
992 synchronized (mNetworkForNetId) {
993 nai = mNetworkForNetId.get(vpnNetId);
994 }
995 if (nai != null) return nai.network;
996 }
997 nai = getDefaultNetwork();
998 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
999 return nai != null ? nai.network : null;
1000 }
1001
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001002 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1003 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001004 final int uid = Binder.getCallingUid();
1005 NetworkState state = getUnfilteredActiveNetworkState(uid);
1006 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001007 }
1008
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001009 @Override
1010 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1011 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001012 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1013 filterNetworkStateForUid(state, uid);
1014 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001015 }
1016
1017 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 public NetworkInfo getNetworkInfo(int networkType) {
1019 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001020 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001021 if (getVpnUnderlyingNetworks(uid) != null) {
1022 // A VPN is active, so we may need to return one of its underlying networks. This
1023 // information is not available in LegacyTypeTracker, so we have to get it from
1024 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001025 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001026 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001027 filterNetworkStateForUid(state, uid);
1028 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001029 }
1030 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001031 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001032 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 }
1034
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001035 @Override
1036 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1037 enforceAccessPermission();
1038 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001039 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001040 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001041 final NetworkState state = nai.getNetworkState();
1042 filterNetworkStateForUid(state, uid);
1043 return state.networkInfo;
1044 } else {
1045 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001046 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001047 }
1048
1049 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 public NetworkInfo[] getAllNetworkInfo() {
1051 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001052 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001053 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1054 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001055 NetworkInfo info = getNetworkInfo(networkType);
1056 if (info != null) {
1057 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001060 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 }
1062
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001063 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001064 public Network getNetworkForType(int networkType) {
1065 enforceAccessPermission();
1066 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001067 NetworkState state = getFilteredNetworkState(networkType, uid);
1068 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1069 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001070 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001071 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001072 }
1073
1074 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001075 public Network[] getAllNetworks() {
1076 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001077 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001078 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001079 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001080 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001081 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001082 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001083 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001084 }
1085
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001086 @Override
1087 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1088 // The basic principle is: if an app's traffic could possibly go over a
1089 // network, without the app doing anything multinetwork-specific,
1090 // (hence, by "default"), then include that network's capabilities in
1091 // the array.
1092 //
1093 // In the normal case, app traffic only goes over the system's default
1094 // network connection, so that's the only network returned.
1095 //
1096 // With a VPN in force, some app traffic may go into the VPN, and thus
1097 // over whatever underlying networks the VPN specifies, while other app
1098 // traffic may go over the system default network (e.g.: a split-tunnel
1099 // VPN, or an app disallowed by the VPN), so the set of networks
1100 // returned includes the VPN's underlying networks and the system
1101 // default.
1102 enforceAccessPermission();
1103
1104 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1105
1106 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001107 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001108 if (nc != null) {
1109 result.put(nai.network, nc);
1110 }
1111
1112 if (!mLockdownEnabled) {
1113 synchronized (mVpns) {
1114 Vpn vpn = mVpns.get(userId);
1115 if (vpn != null) {
1116 Network[] networks = vpn.getUnderlyingNetworks();
1117 if (networks != null) {
1118 for (Network network : networks) {
1119 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001120 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001121 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001122 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001123 }
1124 }
1125 }
1126 }
1127 }
1128 }
1129
1130 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1131 out = result.values().toArray(out);
1132 return out;
1133 }
1134
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001135 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001136 public boolean isNetworkSupported(int networkType) {
1137 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001138 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001139 }
1140
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001141 /**
1142 * Return LinkProperties for the active (i.e., connected) default
1143 * network interface. It is assumed that at most one default network
1144 * is active at a time. If more than one is active, it is indeterminate
1145 * which will be returned.
1146 * @return the ip properties for the active network, or {@code null} if
1147 * none is active
1148 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001149 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001150 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001151 enforceAccessPermission();
1152 final int uid = Binder.getCallingUid();
1153 NetworkState state = getUnfilteredActiveNetworkState(uid);
1154 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001155 }
1156
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001157 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001158 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001159 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001160 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1161 if (nai != null) {
1162 synchronized (nai) {
1163 return new LinkProperties(nai.linkProperties);
1164 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001165 }
1166 return null;
1167 }
1168
Robert Greenwalt12e67352014-05-13 21:41:06 -07001169 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001170 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001171 public LinkProperties getLinkProperties(Network network) {
1172 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001173 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001174 if (nai != null) {
1175 synchronized (nai) {
1176 return new LinkProperties(nai.linkProperties);
1177 }
1178 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001179 return null;
1180 }
1181
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001182 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001183 if (nai != null) {
1184 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001185 if (nai.networkCapabilities != null) {
1186 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001187 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001188 }
1189 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001190 return null;
1191 }
1192
1193 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001194 public NetworkCapabilities getNetworkCapabilities(Network network) {
1195 enforceAccessPermission();
1196 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1197 }
1198
1199 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001200 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001201 // Require internal since we're handing out IMSI details
1202 enforceConnectivityInternalPermission();
1203
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001204 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001205 for (Network network : getAllNetworks()) {
1206 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1207 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001208 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001209 }
1210 }
1211 return result.toArray(new NetworkState[result.size()]);
1212 }
1213
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001214 @Override
1215 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1216 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001217 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001218 final long token = Binder.clearCallingIdentity();
1219 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001220 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1221 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001222 try {
1223 return mPolicyManager.getNetworkQuotaInfo(state);
1224 } catch (RemoteException e) {
1225 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001226 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001227 return null;
1228 } finally {
1229 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001230 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001231 }
1232
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001233 @Override
1234 public boolean isActiveNetworkMetered() {
1235 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001236
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001237 final NetworkInfo info = getActiveNetworkInfo();
1238 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001239 }
1240
Jeff Sharkey216c1812012-08-05 14:29:23 -07001241 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1242 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001243 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001244 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001245 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001246 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001247 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001248
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001249 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 * Ensure that a network route exists to deliver traffic to the specified
1251 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001252 * @param networkType the type of the network over which traffic to the
1253 * specified host is to be routed
1254 * @param hostAddress the IP address of the host to which the route is
1255 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 * @return {@code true} on success, {@code false} on failure
1257 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001258 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001260 if (mProtectedNetworks.contains(networkType)) {
1261 enforceConnectivityInternalPermission();
1262 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001263
Chad Brubakerc0234532014-02-14 13:24:29 -08001264 InetAddress addr;
1265 try {
1266 addr = InetAddress.getByAddress(hostAddress);
1267 } catch (UnknownHostException e) {
1268 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1269 return false;
1270 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001273 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 return false;
1275 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001276
1277 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1278 if (nai == null) {
1279 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1280 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1281 } else {
1282 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1283 }
1284 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001285 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001286
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001287 DetailedState netState;
1288 synchronized (nai) {
1289 netState = nai.networkInfo.getDetailedState();
1290 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001291
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001292 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001293 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001294 log("requestRouteToHostAddress on down network "
1295 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001296 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001297 }
1298 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001300
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001301 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001302 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001303 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001304 LinkProperties lp;
1305 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001306 synchronized (nai) {
1307 lp = nai.linkProperties;
1308 netId = nai.network.netId;
1309 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001310 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001311 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1312 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001313 } finally {
1314 Binder.restoreCallingIdentity(token);
1315 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001316 }
1317
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001318 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001319 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001320 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001321 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001322 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001323 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001324 if (bestRoute.getGateway().equals(addr)) {
1325 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001326 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001327 } else {
1328 // if we will connect to this through another route, add a direct route
1329 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001330 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001331 }
1332 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001333 if (DBG) log("Adding legacy route " + bestRoute +
1334 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001335 try {
1336 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1337 } catch (Exception e) {
1338 // never crash - catch them all
1339 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001340 return false;
1341 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001342 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 }
1344
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001345 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1346 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001347 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001348 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001349 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001350 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001351 }
1352
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001353 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001354 // skip update when we've already applied rules
1355 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1356 if (oldRules == uidRules) return;
1357
1358 mUidRules.put(uid, uidRules);
1359 }
1360
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001361 // TODO: notify UID when it has requested targeted updates
1362 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001363
1364 @Override
1365 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001366 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001367 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001368 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001369 }
1370
1371 synchronized (mRulesLock) {
1372 mMeteredIfaces.clear();
1373 for (String iface : meteredIfaces) {
1374 mMeteredIfaces.add(iface);
1375 }
1376 }
1377 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001378
1379 @Override
1380 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1381 // caller is NPMS, since we only register with them
1382 if (LOGD_RULES) {
1383 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1384 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001385 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001386
1387 @Override
1388 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1389 if (LOGD_RULES) {
1390 // caller is NPMS, since we only register with them
1391 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1392 + whitelisted + ")");
1393 }
1394 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001395 };
1396
Robin Lee3b3dd942015-05-12 18:14:58 +01001397 /**
1398 * Require that the caller is either in the same user or has appropriate permission to interact
1399 * across users.
1400 *
1401 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1402 */
1403 private void enforceCrossUserPermission(int userId) {
1404 if (userId == UserHandle.getCallingUserId()) {
1405 // Not a cross-user call.
1406 return;
1407 }
1408 mContext.enforceCallingOrSelfPermission(
1409 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1410 "ConnectivityService");
1411 }
1412
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001413 private void enforceInternetPermission() {
1414 mContext.enforceCallingOrSelfPermission(
1415 android.Manifest.permission.INTERNET,
1416 "ConnectivityService");
1417 }
1418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001420 mContext.enforceCallingOrSelfPermission(
1421 android.Manifest.permission.ACCESS_NETWORK_STATE,
1422 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 }
1424
1425 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001426 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
1428
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001429 private void enforceTetherAccessPermission() {
1430 mContext.enforceCallingOrSelfPermission(
1431 android.Manifest.permission.ACCESS_NETWORK_STATE,
1432 "ConnectivityService");
1433 }
1434
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001435 private void enforceConnectivityInternalPermission() {
1436 mContext.enforceCallingOrSelfPermission(
1437 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1438 "ConnectivityService");
1439 }
1440
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001441 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001442 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001443 }
1444
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001445 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001446 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001447 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001448 }
1449
1450 private void sendInetConditionBroadcast(NetworkInfo info) {
1451 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1452 }
1453
Wink Saville628b0852011-08-04 15:01:58 -07001454 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001455 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001456 info = new NetworkInfo(info);
1457 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001458 }
1459
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001460 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001461 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001462 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 if (info.isFailover()) {
1464 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1465 info.setFailover(false);
1466 }
1467 if (info.getReason() != null) {
1468 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1469 }
1470 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001471 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1472 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001474 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001475 return intent;
1476 }
1477
1478 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1479 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1480 }
1481
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001482 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001483 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1484 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1485 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001486 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001487 final long ident = Binder.clearCallingIdentity();
1488 try {
1489 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1490 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1491 } finally {
1492 Binder.restoreCallingIdentity(ident);
1493 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001494 }
1495
Mike Lockwood0f79b542009-08-14 14:18:49 -04001496 private void sendStickyBroadcast(Intent intent) {
1497 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001498 if (!mSystemReady) {
1499 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001500 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001501 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001502 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001503 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001504 }
1505
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001506 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001507 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001508 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001509 final NetworkInfo ni = intent.getParcelableExtra(
1510 ConnectivityManager.EXTRA_NETWORK_INFO);
1511 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1512 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1513 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001514 } else {
1515 BroadcastOptions opts = BroadcastOptions.makeBasic();
1516 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1517 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001518 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001519 final IBatteryStats bs = BatteryStatsService.getService();
1520 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001521 bs.noteConnectivityChanged(intent.getIntExtra(
1522 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1523 ni != null ? ni.getState().toString() : "?");
1524 } catch (RemoteException e) {
1525 }
1526 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001527 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001528 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001529 } finally {
1530 Binder.restoreCallingIdentity(ident);
1531 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001532 }
1533 }
1534
1535 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001536 loadGlobalProxy();
1537
Mike Lockwood0f79b542009-08-14 14:18:49 -04001538 synchronized(this) {
1539 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001540 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001541 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001542 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001543 }
1544 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001545 // load the global proxy at startup
1546 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001547
Robin Lee244ce8e2016-01-05 18:03:46 +00001548 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1549 // for user to unlock device too.
1550 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001551
Erik Klineda4bfa82015-04-30 12:58:40 +09001552 // Configure whether mobile data is always on.
1553 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1554
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001555 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001556
1557 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 }
1559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001561 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001562 *
1563 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001564 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001565 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001566 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1567 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001568
1569 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001570 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001571
Robert Greenwalt7b816022014-04-18 15:25:25 -07001572 if (networkAgent.networkCapabilities.hasTransport(
1573 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001574 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1575 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001576 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001577 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001578 } else if (networkAgent.networkCapabilities.hasTransport(
1579 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001580 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1581 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001582 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001583 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001584 } else {
1585 // do not track any other networks
1586 timeout = 0;
1587 }
1588
Robert Greenwalt7b816022014-04-18 15:25:25 -07001589 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001590 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001591 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001592 } catch (Exception e) {
1593 // You shall not crash!
1594 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001595 }
1596 }
1597 }
1598
1599 /**
1600 * Remove data activity tracking when network disconnects.
1601 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001602 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1603 final String iface = networkAgent.linkProperties.getInterfaceName();
1604 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001605
Robert Greenwalt7b816022014-04-18 15:25:25 -07001606 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1607 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001608 try {
1609 // the call fails silently if no idletimer setup for this interface
1610 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001611 } catch (Exception e) {
1612 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001613 }
1614 }
1615 }
1616
1617 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001618 * Reads the network specific MTU size from reources.
1619 * and set it on it's iface.
1620 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001621 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1622 final String iface = newLp.getInterfaceName();
1623 final int mtu = newLp.getMtu();
1624 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1625 if (VDBG) log("identical MTU - not setting");
1626 return;
1627 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001628
Robert Greenwalt43074032014-08-15 17:53:05 -07001629 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001630 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001631 return;
1632 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001633
w1997615afd812014-08-05 15:18:11 -07001634 // Cannot set MTU without interface name
1635 if (TextUtils.isEmpty(iface)) {
1636 loge("Setting MTU size with null iface.");
1637 return;
1638 }
1639
Robert Greenwalt7b816022014-04-18 15:25:25 -07001640 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001641 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001642 mNetd.setMtu(iface, mtu);
1643 } catch (Exception e) {
1644 Slog.e(TAG, "exception in setMtu()" + e);
1645 }
1646 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001647
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001648 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001649 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1650
1651 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001652 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001653 protected int getDefaultTcpRwnd() {
1654 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1655 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001656
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001657 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1658 if (isDefaultNetwork(nai) == false) {
1659 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001660 }
1661
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001662 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1663 String[] values = null;
1664 if (tcpBufferSizes != null) {
1665 values = tcpBufferSizes.split(",");
1666 }
1667
1668 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001669 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001670 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1671 values = tcpBufferSizes.split(",");
1672 }
1673
1674 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1675
1676 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001677 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001678
1679 final String prefix = "/sys/kernel/ipv4/tcp_";
1680 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1681 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1682 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1683 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1684 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1685 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1686 mCurrentTcpBufferSizes = tcpBufferSizes;
1687 } catch (IOException e) {
1688 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001689 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001690
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001691 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001692 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001693 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1694 if (rwndValue != 0) {
1695 SystemProperties.set(sysctlKey, rwndValue.toString());
1696 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001697 }
1698
Mattias Falk8b47b362011-08-23 14:15:13 +02001699 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001700 /*
1701 * Tell the VMs to toss their DNS caches
1702 */
1703 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1704 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001705 /*
1706 * Connectivity events can happen before boot has completed ...
1707 */
1708 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001709 final long ident = Binder.clearCallingIdentity();
1710 try {
1711 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1712 } finally {
1713 Binder.restoreCallingIdentity(ident);
1714 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001715 }
1716
Robert Greenwalt562cc542014-05-15 18:07:26 -07001717 @Override
1718 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001719 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1720 NETWORK_RESTORE_DELAY_PROP_NAME);
1721 if(restoreDefaultNetworkDelayStr != null &&
1722 restoreDefaultNetworkDelayStr.length() != 0) {
1723 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001724 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001725 } catch (NumberFormatException e) {
1726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001728 // if the system property isn't set, use the value for the apn type
1729 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1730
1731 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1732 (mNetConfigs[networkType] != null)) {
1733 ret = mNetConfigs[networkType].restoreTime;
1734 }
1735 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 }
1737
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001738 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001739 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001740 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001741 }
1742 return false;
1743 }
1744
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001745 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1746 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1747 final long DIAG_TIME_MS = 5000;
1748 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1749 // Start gathering diagnostic information.
1750 netDiags.add(new NetworkDiagnostics(
1751 nai.network,
1752 new LinkProperties(nai.linkProperties), // Must be a copy.
1753 DIAG_TIME_MS));
1754 }
1755
1756 for (NetworkDiagnostics netDiag : netDiags) {
1757 pw.println();
1758 netDiag.waitForMeasurements();
1759 netDiag.dump(pw);
1760 }
1761 }
1762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001764 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1765 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001766 if (mContext.checkCallingOrSelfPermission(
1767 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001769 pw.println("Permission Denial: can't dump ConnectivityService " +
1770 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1771 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 return;
1773 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001774
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001775 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001776 dumpNetworkDiagnostics(pw);
1777 return;
1778 }
Erik Kline379747a2015-06-05 17:47:34 +09001779
Lorenzo Colittie3805462015-06-03 11:18:24 +09001780 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001781 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001782 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001783 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001784 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001785 pw.println();
1786
Paul Jensen85cf78e2015-06-25 13:25:07 -04001787 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001788 pw.print("Active default network: ");
1789 if (defaultNai == null) {
1790 pw.println("none");
1791 } else {
1792 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001794 pw.println();
1795
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001796 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001797 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001798 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1799 pw.println(nai.toString());
1800 pw.increaseIndent();
1801 pw.println("Requests:");
1802 pw.increaseIndent();
1803 for (int i = 0; i < nai.networkRequests.size(); i++) {
1804 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001805 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001806 pw.decreaseIndent();
1807 pw.println("Lingered:");
1808 pw.increaseIndent();
1809 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1810 pw.decreaseIndent();
1811 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001812 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001813 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001814 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001815
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001816 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001817 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001818 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1819 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001820 }
1821 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001822 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001823
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001824 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001825
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001826 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001827 pw.print("mNetTransitionWakeLock: currently " +
1828 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1829 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1830 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1831 } else {
1832 pw.println(", last requested never");
1833 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001834 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001835
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001836 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001837 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001838
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001839 pw.println();
1840 mKeepaliveTracker.dump(pw);
1841
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001842 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001843
Lorenzo Colittie3805462015-06-03 11:18:24 +09001844 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001845 pw.println();
1846 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001847 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001848 for(int i = 0; i < mInetLog.size(); i++) {
1849 pw.println(mInetLog.get(i));
1850 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001851 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001852 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001853
1854 if (argsContain(args, "--short") == false) {
1855 pw.println();
1856 synchronized (mValidationLogs) {
1857 pw.println("mValidationLogs (most recent first):");
1858 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1859 pw.println(p.first);
1860 pw.increaseIndent();
1861 p.second.dump(fd, pw, args);
1862 pw.decreaseIndent();
1863 }
1864 }
Erik Kline7523eb32015-07-09 18:24:03 +09001865
1866 pw.println();
1867 pw.println("mNetworkRequestInfoLogs (most recent first):");
1868 pw.increaseIndent();
1869 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1870 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 }
1873
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001874 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001875 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001876 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001877 if (officialNai != null && officialNai.equals(nai)) return true;
1878 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001879 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001880 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001881 " - " + nai);
1882 }
1883 return false;
1884 }
1885
Paul Jensenc8b9a742014-09-30 15:37:41 -04001886 private boolean isRequest(NetworkRequest request) {
Erik Kline371c7b72016-03-22 17:04:20 +09001887 return mNetworkRequests.get(request).isRequest();
Paul Jensenc8b9a742014-09-30 15:37:41 -04001888 }
1889
Robert Greenwalt42acef32009-08-12 16:08:25 -07001890 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001891 private class NetworkStateTrackerHandler extends Handler {
1892 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001893 super(looper);
1894 }
1895
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001896 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001898 default:
1899 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07001900 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001901 handleAsyncChannelHalfConnect(msg);
1902 break;
1903 }
1904 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1905 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1906 if (nai != null) nai.asyncChannel.disconnect();
1907 break;
1908 }
1909 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1910 handleAsyncChannelDisconnected(msg);
1911 break;
1912 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001913 }
1914 return true;
1915 }
1916
1917 private void maybeHandleNetworkAgentMessage(Message msg) {
1918 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1919 if (nai == null) {
1920 if (VDBG) {
1921 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
1922 log(String.format("%s from unknown NetworkAgent", what));
1923 }
1924 return;
1925 }
1926
1927 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001928 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001929 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
1930 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1931 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
1932 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07001933 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001934 if (nai.created && !nai.networkCapabilities.equalImmutableCapabilities(
1935 networkCapabilities)) {
1936 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
1937 + nai.networkCapabilities + " -> " + networkCapabilities);
1938 }
1939 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001940 break;
1941 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001942 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001943 if (VDBG) {
1944 log("Update of LinkProperties for " + nai.name() +
1945 "; created=" + nai.created);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001946 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001947 LinkProperties oldLp = nai.linkProperties;
1948 synchronized (nai) {
1949 nai.linkProperties = (LinkProperties)msg.obj;
1950 }
1951 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001952 break;
1953 }
1954 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001955 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001956 updateNetworkInfo(nai, info);
1957 break;
1958 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001959 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07001960 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001961 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001962 break;
1963 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001964 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001965 try {
1966 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001967 } catch (Exception e) {
1968 // Never crash!
1969 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001970 }
1971 break;
1972 }
1973 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001974 try {
1975 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001976 } catch (Exception e) {
1977 // Never crash!
1978 loge("Exception in removeVpnUidRanges: " + e);
1979 }
1980 break;
1981 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001982 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001983 if (nai.created && !nai.networkMisc.explicitlySelected) {
1984 loge("ERROR: created network explicitly selected.");
1985 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001986 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001987 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07001988 break;
1989 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001990 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001991 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
1992 break;
1993 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001994 }
1995 }
1996
1997 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
1998 switch (msg.what) {
1999 default:
2000 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002001 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002002 final NetworkAgentInfo nai;
2003 synchronized (mNetworkForNetId) {
2004 nai = mNetworkForNetId.get(msg.arg2);
2005 }
2006 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002007 final boolean valid =
2008 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen232437312016-04-06 09:51:26 -04002009 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2010 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002011 if (valid != nai.lastValidated) {
2012 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002013 nai.lastValidated = valid;
2014 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002015 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002016 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2017 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002018 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002019 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002020 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002021 Bundle redirectUrlBundle = new Bundle();
2022 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002023 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002024 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002025 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002026 0, redirectUrlBundle);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002027 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002028 break;
2029 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002030 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002031 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002032 if (isLiveNetworkAgent(nai, msg.what)) {
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002033 handleLingerComplete(nai);
2034 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002035 break;
2036 }
Paul Jensen869868be2014-05-15 10:33:05 -04002037 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002038 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002039 final boolean visible = (msg.arg1 != 0);
2040 final NetworkAgentInfo nai;
2041 synchronized (mNetworkForNetId) {
2042 nai = mNetworkForNetId.get(netId);
2043 }
2044 // If captive portal status has changed, update capabilities.
2045 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2046 nai.lastCaptivePortalDetected = visible;
2047 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002048 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002049 }
2050 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002051 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002052 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002053 if (nai == null) {
2054 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2055 break;
2056 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002057 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002058 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2059 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002060 }
Paul Jensen869868be2014-05-15 10:33:05 -04002061 break;
2062 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002063 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002064 return true;
2065 }
2066
2067 @Override
2068 public void handleMessage(Message msg) {
2069 if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) {
2070 maybeHandleNetworkAgentMessage(msg);
2071 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002072 }
2073 }
2074
Paul Jensen85cf78e2015-06-25 13:25:07 -04002075 private void linger(NetworkAgentInfo nai) {
2076 nai.lingering = true;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002077 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_LINGER);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002078 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2079 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2080 }
2081
Paul Jensen0cc17322014-11-25 15:26:53 -05002082 // Cancel any lingering so the linger timeout doesn't teardown a network.
2083 // This should be called when a network begins satisfying a NetworkRequest.
2084 // Note: depending on what state the NetworkMonitor is in (e.g.,
2085 // if it's awaiting captive portal login, or if validation failed), this
2086 // may trigger a re-evaluation of the network.
2087 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002088 nai.networkLingered.clear();
2089 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002090 nai.lingering = false;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002091 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_UNLINGER);
Paul Jensen0cc17322014-11-25 15:26:53 -05002092 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002093 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2094 }
2095
Robert Greenwalt7b816022014-04-18 15:25:25 -07002096 private void handleAsyncChannelHalfConnect(Message msg) {
2097 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002098 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002099 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2100 if (VDBG) log("NetworkFactory connected");
2101 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002102 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Erik Kline371c7b72016-03-22 17:04:20 +09002103 if (!nri.isRequest()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002104 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002105 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002106 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002107 }
2108 } else {
2109 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002110 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002111 }
2112 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2113 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2114 if (VDBG) log("NetworkAgent connected");
2115 // A network agent has requested a connection. Establish the connection.
2116 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2117 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2118 } else {
2119 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002120 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002121 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002122 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002123 synchronized (mNetworkForNetId) {
2124 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002125 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002126 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002127 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002128 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002129 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002130 }
2131 }
2132 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002133
Robert Greenwalt7b816022014-04-18 15:25:25 -07002134 private void handleAsyncChannelDisconnected(Message msg) {
2135 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2136 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002137 if (DBG) {
2138 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2139 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002140 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002141 // TODO - if we move the logic to the network agent (have them disconnect
2142 // because they lost all their requests or because their score isn't good)
2143 // then they would disconnect organically, report their new state and then
2144 // disconnect the channel.
2145 if (nai.networkInfo.isConnected()) {
2146 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2147 null, null);
2148 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002149 final boolean wasDefault = isDefaultNetwork(nai);
2150 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002151 mDefaultInetConditionPublished = 0;
2152 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002153 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002154 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2155 // by other networks that are already connected. Perhaps that can be done by
2156 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2157 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002158 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002159 mKeepaliveTracker.handleStopAllKeepalives(nai,
2160 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002161 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002162 mNetworkAgentInfos.remove(msg.replyTo);
2163 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002164 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002165 // Remove the NetworkAgent, but don't mark the netId as
2166 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002167 mNetworkForNetId.remove(nai.network.netId);
2168 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002169 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002170 for (int i = 0; i < nai.networkRequests.size(); i++) {
2171 NetworkRequest request = nai.networkRequests.valueAt(i);
2172 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2173 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2174 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002175 sendUpdatedScoreToFactories(request, 0);
2176 }
2177 }
2178 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2179 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002180 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002181 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002182 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002183 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002184 rematchAllNetworksAndRequests(null, 0);
Pierre Imai04e222252016-04-12 18:02:58 +09002185 if (wasDefault && getDefaultNetwork() == null) {
2186 // Log that we lost the default network and there is no replacement.
Hugo Benichi5f16f762016-04-20 12:09:33 +09002187 logDefaultNetworkEvent(null, nai);
Pierre Imai04e222252016-04-12 18:02:58 +09002188 }
Paul Jensen62d30802015-06-17 14:42:30 -04002189 if (nai.created) {
2190 // Tell netd to clean up the configuration for this network
2191 // (routing rules, DNS, etc).
2192 // This may be slow as it requires a lot of netd shelling out to ip and
2193 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2194 // after we've rematched networks with requests which should make a potential
2195 // fallback network the default or requested a new network from the
2196 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2197 // long time.
2198 try {
2199 mNetd.removeNetwork(nai.network.netId);
2200 } catch (Exception e) {
2201 loge("Exception removing network: " + e);
2202 }
2203 }
2204 synchronized (mNetworkForNetId) {
2205 mNetIdInUse.delete(nai.network.netId);
2206 }
2207 } else {
2208 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2209 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002210 }
2211 }
2212
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002213 // If this method proves to be too slow then we can maintain a separate
2214 // pendingIntent => NetworkRequestInfo map.
2215 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2216 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2217 Intent intent = pendingIntent.getIntent();
2218 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2219 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2220 if (existingPendingIntent != null &&
2221 existingPendingIntent.getIntent().filterEquals(intent)) {
2222 return entry.getValue();
2223 }
2224 }
2225 return null;
2226 }
2227
2228 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2229 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2230
2231 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2232 if (existingRequest != null) { // remove the existing request.
2233 if (DBG) log("Replacing " + existingRequest.request + " with "
2234 + nri.request + " because their intents matched.");
2235 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2236 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002237 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002238 }
2239
Erik Klineda4bfa82015-04-30 12:58:40 +09002240 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002241 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002242 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002243 if (!nri.isRequest()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002244 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002245 if (nri.request.networkCapabilities.hasSignalStrength() &&
2246 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2247 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002248 }
2249 }
2250 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002251 rematchAllNetworksAndRequests(null, 0);
Erik Kline371c7b72016-03-22 17:04:20 +09002252 if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002253 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002254 }
2255 }
2256
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002257 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2258 int callingUid) {
2259 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2260 if (nri != null) {
2261 handleReleaseNetworkRequest(nri.request, callingUid);
2262 }
2263 }
2264
Paul Jensen99364842014-12-09 11:43:45 -05002265 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002266 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2267 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002268 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002269 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002270 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2271 // If this Network is already the highest scoring Network for a request, or if
2272 // there is hope for it to become one if it validated, then it is needed.
Erik Kline371c7b72016-03-22 17:04:20 +09002273 if (nri.isRequest() && nai.satisfies(nri.request) &&
Paul Jensene0988542015-06-25 15:30:08 -04002274 (nai.networkRequests.get(nri.request.requestId) != null ||
2275 // Note that this catches two important cases:
2276 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2277 // is currently satisfying the request. This is desirable when
2278 // cellular ends up validating but WiFi does not.
2279 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002280 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002281 // WiFi ends up validating and out scoring cellular.
2282 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2283 nai.getCurrentScoreAsValidated())) {
2284 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002285 }
2286 }
Paul Jensene0988542015-06-25 15:30:08 -04002287 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002288 }
2289
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002290 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2291 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002292 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002293 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002294 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2295 return;
2296 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002297 if (VDBG || (DBG && nri.isRequest())) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002298 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002299 mNetworkRequests.remove(request);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002300 synchronized (mUidToNetworkRequestCount) {
2301 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2302 if (requests < 1) {
2303 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2304 nri.mUid);
2305 } else if (requests == 1) {
2306 mUidToNetworkRequestCount.removeAt(
2307 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2308 } else {
2309 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2310 }
2311 }
Erik Kline7523eb32015-07-09 18:24:03 +09002312 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002313 if (nri.isRequest()) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002314 // Find all networks that are satisfying this request and remove the request
2315 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002316 // TODO - it's my understanding that for a request there is only a single
2317 // network satisfying it, so this loop is wasteful
2318 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002319 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2320 if (nai.networkRequests.get(nri.request.requestId) != null) {
2321 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002322 if (VDBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002323 log(" Removing from current network " + nai.name() +
2324 ", leaving " + nai.networkRequests.size() +
2325 " requests.");
2326 }
Paul Jensen99364842014-12-09 11:43:45 -05002327 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002328 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002329 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002330 } else {
2331 // suspect there should only be one pass through here
2332 // but if any were kept do the check below
2333 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002334 }
2335 }
2336 }
2337
Robert Greenwalt51481852015-01-08 14:43:31 -08002338 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2339 if (nai != null) {
2340 mNetworkForRequestId.remove(nri.request.requestId);
2341 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002342 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002343 // that a network connected to serve it, even though the network was already
2344 // connected. Now that this request has gone away, we might have to pretend
2345 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002346 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002347 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2348 boolean doRemove = true;
2349 if (wasKept) {
2350 // check if any of the remaining requests for this network are for the
2351 // same legacy type - if so, don't remove the nai
2352 for (int i = 0; i < nai.networkRequests.size(); i++) {
2353 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2354 if (otherRequest.legacyType == nri.request.legacyType &&
2355 isRequest(otherRequest)) {
2356 if (DBG) log(" still have other legacy request - leaving");
2357 doRemove = false;
2358 }
2359 }
2360 }
2361
2362 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002363 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002364 }
2365 }
2366
Robert Greenwalta67be032014-05-16 15:49:14 -07002367 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002368 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2369 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002370 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002371 } else {
2372 // listens don't have a singular affectedNetwork. Check all networks to see
2373 // if this listen request applies and remove it.
2374 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2375 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002376 if (nri.request.networkCapabilities.hasSignalStrength() &&
2377 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2378 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002379 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002380 }
2381 }
2382 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2383 }
2384 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002385
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002386 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2387 enforceConnectivityInternalPermission();
2388 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2389 accept ? 1 : 0, always ? 1: 0, network));
2390 }
2391
2392 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2393 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2394 " accept=" + accept + " always=" + always);
2395
2396 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2397 if (nai == null) {
2398 // Nothing to do.
2399 return;
2400 }
2401
2402 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002403 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002404 return;
2405 }
2406
2407 if (!nai.networkMisc.explicitlySelected) {
2408 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2409 }
2410
2411 if (accept != nai.networkMisc.acceptUnvalidated) {
2412 int oldScore = nai.getCurrentScore();
2413 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002414 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002415 sendUpdatedScoreToFactories(nai);
2416 }
2417
2418 if (always) {
2419 nai.asyncChannel.sendMessage(
2420 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2421 }
2422
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002423 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002424 // Tell the NetworkAgent to not automatically reconnect to the network.
2425 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2426 // Teardown the nework.
2427 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002428 }
2429
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002430 }
2431
2432 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002433 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002434 mHandler.sendMessageDelayed(
2435 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2436 PROMPT_UNVALIDATED_DELAY_MS);
2437 }
2438
2439 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002440 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002441 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2442
2443 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2444 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002445 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002446 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002447 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2448 return;
2449 }
2450
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002451 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002452 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002453 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2454 intent.setClassName("com.android.settings",
2455 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002456
2457 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2458 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2459 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002460 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002461 }
2462
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002463 private class InternalHandler extends Handler {
2464 public InternalHandler(Looper looper) {
2465 super(looper);
2466 }
2467
2468 @Override
2469 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002470 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002471 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002472 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002473 String causedBy = null;
2474 synchronized (ConnectivityService.this) {
2475 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2476 mNetTransitionWakeLock.isHeld()) {
2477 mNetTransitionWakeLock.release();
2478 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002479 } else {
2480 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002481 }
2482 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002483 if (VDBG) {
2484 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2485 log("Failed to find a new network - expiring NetTransition Wakelock");
2486 } else {
2487 log("NetTransition Wakelock (" +
2488 (causedBy == null ? "unknown" : causedBy) +
2489 " cleared because we found a replacement network");
2490 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002491 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002492 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002493 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002494 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002495 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002496 break;
2497 }
Jason Monkdecd2952013-10-10 14:02:51 -04002498 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002499 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002500 break;
2501 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002502 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002503 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2504 break;
2505 }
2506 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2507 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002508 break;
2509 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002510 case EVENT_REGISTER_NETWORK_AGENT: {
2511 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2512 break;
2513 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002514 case EVENT_REGISTER_NETWORK_REQUEST:
2515 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002516 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002517 break;
2518 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002519 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2520 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002521 handleRegisterNetworkRequestWithIntent(msg);
2522 break;
2523 }
2524 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2525 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2526 break;
2527 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002528 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002529 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002530 break;
2531 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002532 case EVENT_SET_ACCEPT_UNVALIDATED: {
2533 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2534 break;
2535 }
2536 case EVENT_PROMPT_UNVALIDATED: {
2537 handlePromptUnvalidated((Network) msg.obj);
2538 break;
2539 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002540 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2541 handleMobileDataAlwaysOn();
2542 break;
2543 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002544 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2545 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2546 mKeepaliveTracker.handleStartKeepalive(msg);
2547 break;
2548 }
2549 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2550 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2551 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2552 int slot = msg.arg1;
2553 int reason = msg.arg2;
2554 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2555 break;
2556 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002557 case EVENT_SYSTEM_READY: {
2558 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2559 nai.networkMonitor.systemReady = true;
2560 }
2561 break;
2562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 }
2564 }
2565 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002566
2567 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002568 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002569 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002570 if (isTetheringSupported()) {
2571 return mTethering.tether(iface);
2572 } else {
2573 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2574 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002575 }
2576
2577 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002578 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002579 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002580
2581 if (isTetheringSupported()) {
2582 return mTethering.untether(iface);
2583 } else {
2584 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2585 }
2586 }
2587
2588 // javadoc from interface
2589 public int getLastTetherError(String iface) {
2590 enforceTetherAccessPermission();
2591
2592 if (isTetheringSupported()) {
2593 return mTethering.getLastTetherError(iface);
2594 } else {
2595 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2596 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002597 }
2598
2599 // TODO - proper iface API for selection by property, inspection, etc
2600 public String[] getTetherableUsbRegexs() {
2601 enforceTetherAccessPermission();
2602 if (isTetheringSupported()) {
2603 return mTethering.getTetherableUsbRegexs();
2604 } else {
2605 return new String[0];
2606 }
2607 }
2608
2609 public String[] getTetherableWifiRegexs() {
2610 enforceTetherAccessPermission();
2611 if (isTetheringSupported()) {
2612 return mTethering.getTetherableWifiRegexs();
2613 } else {
2614 return new String[0];
2615 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002616 }
2617
Danica Chang6fdd0c62010-08-11 14:54:43 -07002618 public String[] getTetherableBluetoothRegexs() {
2619 enforceTetherAccessPermission();
2620 if (isTetheringSupported()) {
2621 return mTethering.getTetherableBluetoothRegexs();
2622 } else {
2623 return new String[0];
2624 }
2625 }
2626
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002627 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002628 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002629 if (isTetheringSupported()) {
2630 return mTethering.setUsbTethering(enable);
2631 } else {
2632 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2633 }
2634 }
2635
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002636 // TODO - move iface listing, queries, etc to new module
2637 // javadoc from interface
2638 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002639 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002640 return mTethering.getTetherableIfaces();
2641 }
2642
2643 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002644 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002645 return mTethering.getTetheredIfaces();
2646 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002647
Robert Greenwalt5a735062010-03-02 17:25:02 -08002648 public String[] getTetheringErroredIfaces() {
2649 enforceTetherAccessPermission();
2650 return mTethering.getErroredIfaces();
2651 }
2652
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002653 public String[] getTetheredDhcpRanges() {
2654 enforceConnectivityInternalPermission();
2655 return mTethering.getTetheredDhcpRanges();
2656 }
2657
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002658 // if ro.tether.denied = true we default to no tethering
2659 // gservices could set the secure setting to 1 though to enable it on a build where it
2660 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002661 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002662 public boolean isTetheringSupported() {
2663 enforceTetherAccessPermission();
2664 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002665 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002666 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2667 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002668 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2669 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002670 mTethering.getTetherableWifiRegexs().length != 0 ||
2671 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2672 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002673 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002674
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002675 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002676 public void startTethering(int type, ResultReceiver receiver,
2677 boolean showProvisioningUi) {
2678 ConnectivityManager.enforceTetherChangePermission(mContext);
2679 if (!isTetheringSupported()) {
2680 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2681 return;
2682 }
2683 mTethering.startTethering(type, receiver, showProvisioningUi);
2684 }
2685
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002686 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002687 public void stopTethering(int type) {
2688 ConnectivityManager.enforceTetherChangePermission(mContext);
2689 mTethering.stopTethering(type);
2690 }
2691
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002692 // Called when we lose the default network and have no replacement yet.
2693 // This will automatically be cleared after X seconds or a new default network
2694 // becomes CONNECTED, whichever happens first. The timer is started by the
2695 // first caller and not restarted by subsequent callers.
2696 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002697 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002698 synchronized (this) {
2699 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002700 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002701 mNetTransitionWakeLock.acquire();
2702 mNetTransitionWakeLockCausedBy = forWhom;
2703 }
2704 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002705 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002706 mNetTransitionWakeLockTimeout);
2707 return;
2708 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002709
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002710 // 100 percent is full good, 0 is full bad.
2711 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002712 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002713 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002714 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002715 }
2716
Paul Jensenbfd17b72015-04-07 12:43:13 -04002717 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002718 enforceAccessPermission();
2719 enforceInternetPermission();
2720
Paul Jensenbfd17b72015-04-07 12:43:13 -04002721 NetworkAgentInfo nai;
2722 if (network == null) {
2723 nai = getDefaultNetwork();
2724 } else {
2725 nai = getNetworkAgentInfoForNetwork(network);
2726 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002727 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2728 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2729 return;
2730 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002731 // Revalidate if the app report does not match our current validated state.
2732 if (hasConnectivity == nai.lastValidated) return;
2733 final int uid = Binder.getCallingUid();
2734 if (DBG) {
2735 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2736 ") by " + uid);
2737 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002738 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002739 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2740 // which isn't meant to work on uncreated networks.
2741 if (!nai.created) return;
2742
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002743 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002744
2745 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2746 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002747 }
2748
Paul Jensencee9b512015-05-06 07:32:40 -04002749 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002750 // this information is already available as a world read/writable jvm property
2751 // so this API change wouldn't have a benifit. It also breaks the passing
2752 // of proxy info to all the JVMs.
2753 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002754 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002755 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002756 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2757 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002758 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002759 }
2760
Paul Jensencee9b512015-05-06 07:32:40 -04002761 public ProxyInfo getProxyForNetwork(Network network) {
2762 if (network == null) return getDefaultProxy();
2763 final ProxyInfo globalProxy = getGlobalProxy();
2764 if (globalProxy != null) return globalProxy;
2765 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2766 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2767 // caller may not have.
2768 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2769 if (nai == null) return null;
2770 synchronized (nai) {
2771 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2772 if (proxyInfo == null) return null;
2773 return new ProxyInfo(proxyInfo);
2774 }
2775 }
2776
Paul Jensene0bef712014-12-10 15:12:18 -05002777 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2778 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2779 // proxy is null then there is no proxy in place).
2780 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2781 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2782 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2783 proxy = null;
2784 }
2785 return proxy;
2786 }
2787
2788 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2789 // better for determining if a new proxy broadcast is necessary:
2790 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2791 // avoid unnecessary broadcasts.
2792 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2793 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2794 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2795 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2796 // all set.
2797 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2798 a = canonicalizeProxyInfo(a);
2799 b = canonicalizeProxyInfo(b);
2800 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2801 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2802 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2803 }
2804
Jason Monk207900c2014-04-25 15:00:09 -04002805 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002806 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002807
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002808 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002809 if (proxyProperties == mGlobalProxy) return;
2810 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2811 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2812
2813 String host = "";
2814 int port = 0;
2815 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002816 String pacFileUrl = "";
2817 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002818 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002819 if (!proxyProperties.isValid()) {
2820 if (DBG)
2821 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2822 return;
2823 }
Jason Monk207900c2014-04-25 15:00:09 -04002824 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002825 host = mGlobalProxy.getHost();
2826 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002827 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002828 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002829 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002830 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002831 } else {
2832 mGlobalProxy = null;
2833 }
2834 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002835 final long token = Binder.clearCallingIdentity();
2836 try {
2837 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2838 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2839 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2840 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002841 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002842 } finally {
2843 Binder.restoreCallingIdentity(token);
2844 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002845
Jason Monkcf0f97a2014-10-02 15:39:38 -04002846 if (mGlobalProxy == null) {
2847 proxyProperties = mDefaultProxy;
2848 }
2849 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002850 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002851 }
2852
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002853 private void loadGlobalProxy() {
2854 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002855 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2856 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2857 String exclList = Settings.Global.getString(res,
2858 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002859 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2860 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002861 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002862 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002863 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002864 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002865 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002866 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002867 if (!proxyProperties.isValid()) {
2868 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2869 return;
2870 }
2871
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002872 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002873 mGlobalProxy = proxyProperties;
2874 }
2875 }
2876 }
2877
Jason Monk207900c2014-04-25 15:00:09 -04002878 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002879 // this information is already available as a world read/writable jvm property
2880 // so this API change wouldn't have a benifit. It also breaks the passing
2881 // of proxy info to all the JVMs.
2882 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002883 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002884 return mGlobalProxy;
2885 }
2886 }
2887
Jason Monk207900c2014-04-25 15:00:09 -04002888 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002889 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002890 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002891 proxy = null;
2892 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002893 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002894 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002895 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002896 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002897 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2898 return;
2899 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002900
2901 // This call could be coming from the PacManager, containing the port of the local
2902 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2903 // global (to get the correct local port), and send a broadcast.
2904 // TODO: Switch PacManager to have its own message to send back rather than
2905 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002906 if ((mGlobalProxy != null) && (proxy != null)
2907 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002908 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2909 mGlobalProxy = proxy;
2910 sendProxyBroadcast(mGlobalProxy);
2911 return;
2912 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002913 mDefaultProxy = proxy;
2914
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002915 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002916 if (!mDefaultProxyDisabled) {
2917 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002918 }
2919 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002920 }
2921
Paul Jensene0bef712014-12-10 15:12:18 -05002922 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2923 // This method gets called when any network changes proxy, but the broadcast only ever contains
2924 // the default proxy (even if it hasn't changed).
2925 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2926 // world where an app might be bound to a non-default network.
2927 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2928 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2929 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2930
2931 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2932 sendProxyBroadcast(getDefaultProxy());
2933 }
2934 }
2935
Robert Greenwalt434203a2010-10-11 16:00:27 -07002936 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002937 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2938 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002939 if (!TextUtils.isEmpty(proxy)) {
2940 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002941 if (data.length == 0) {
2942 return;
2943 }
2944
Robert Greenwalt434203a2010-10-11 16:00:27 -07002945 String proxyHost = data[0];
2946 int proxyPort = 8080;
2947 if (data.length > 1) {
2948 try {
2949 proxyPort = Integer.parseInt(data[1]);
2950 } catch (NumberFormatException e) {
2951 return;
2952 }
2953 }
Jason Monk207900c2014-04-25 15:00:09 -04002954 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002955 setGlobalProxy(p);
2956 }
2957 }
2958
Jason Monk207900c2014-04-25 15:00:09 -04002959 private void sendProxyBroadcast(ProxyInfo proxy) {
2960 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002961 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002962 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002963 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002964 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2965 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002966 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002967 final long ident = Binder.clearCallingIdentity();
2968 try {
2969 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2970 } finally {
2971 Binder.restoreCallingIdentity(ident);
2972 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002973 }
2974
2975 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002976 final private HashMap<Uri, Integer> mUriEventMap;
2977 final private Context mContext;
2978 final private Handler mHandler;
2979
2980 SettingsObserver(Context context, Handler handler) {
2981 super(null);
2982 mUriEventMap = new HashMap<Uri, Integer>();
2983 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002984 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002985 }
2986
Erik Klineda4bfa82015-04-30 12:58:40 +09002987 void observe(Uri uri, int what) {
2988 mUriEventMap.put(uri, what);
2989 final ContentResolver resolver = mContext.getContentResolver();
2990 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002991 }
2992
2993 @Override
2994 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002995 Slog.wtf(TAG, "Should never be reached.");
2996 }
2997
2998 @Override
2999 public void onChange(boolean selfChange, Uri uri) {
3000 final Integer what = mUriEventMap.get(uri);
3001 if (what != null) {
3002 mHandler.obtainMessage(what.intValue()).sendToTarget();
3003 } else {
3004 loge("No matching event to send for URI=" + uri);
3005 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003006 }
3007 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003008
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003009 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003010 Slog.d(TAG, s);
3011 }
3012
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003013 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003014 Slog.e(TAG, s);
3015 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003016
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003017 private static <T> T checkNotNull(T value, String message) {
3018 if (value == null) {
3019 throw new NullPointerException(message);
3020 }
3021 return value;
3022 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003023
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003024 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003025 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003026 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3027 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3028 *
3029 * @param oldPackage Package name of the application which currently controls VPN, which will
3030 * be replaced. If there is no such application, this should should either be
3031 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3032 * @param newPackage Package name of the application which should gain control of VPN, or
3033 * {@code null} to disable.
3034 * @param userId User for whom to prepare the new VPN.
3035 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003036 * @hide
3037 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003038 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003039 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3040 int userId) {
3041 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003042 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003043
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003044 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003045 Vpn vpn = mVpns.get(userId);
3046 if (vpn != null) {
3047 return vpn.prepare(oldPackage, newPackage);
3048 } else {
3049 return false;
3050 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003051 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003052 }
3053
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003054 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003055 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3056 * This method is used by system-privileged apps.
3057 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3058 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3059 *
3060 * @param packageName The package for which authorization state should change.
3061 * @param userId User for whom {@code packageName} is installed.
3062 * @param authorized {@code true} if this app should be able to start a VPN connection without
3063 * explicit user approval, {@code false} if not.
3064 *
Jeff Davidson05542602014-08-11 14:07:27 -07003065 * @hide
3066 */
3067 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003068 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3069 enforceCrossUserPermission(userId);
3070
Jeff Davidson05542602014-08-11 14:07:27 -07003071 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003072 Vpn vpn = mVpns.get(userId);
3073 if (vpn != null) {
3074 vpn.setPackageAuthorization(packageName, authorized);
3075 }
Jeff Davidson05542602014-08-11 14:07:27 -07003076 }
3077 }
3078
3079 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003080 * Configure a TUN interface and return its file descriptor. Parameters
3081 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003082 * and not available in ConnectivityManager. Permissions are checked in
3083 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003084 * @hide
3085 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003086 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003087 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003088 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003089 int user = UserHandle.getUserId(Binder.getCallingUid());
3090 synchronized(mVpns) {
3091 return mVpns.get(user).establish(config);
3092 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003093 }
3094
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003095 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003096 * Start legacy VPN, controlling native daemons as needed. Creates a
3097 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003098 */
3099 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003100 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003101 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003102 final LinkProperties egress = getActiveLinkProperties();
3103 if (egress == null) {
3104 throw new IllegalStateException("Missing active network connection");
3105 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003106 int user = UserHandle.getUserId(Binder.getCallingUid());
3107 synchronized(mVpns) {
3108 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3109 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003110 }
3111
3112 /**
3113 * Return the information of the ongoing legacy VPN. This method is used
3114 * by VpnSettings and not available in ConnectivityManager. Permissions
3115 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003116 */
3117 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003118 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3119 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003120 if (mLockdownEnabled) {
3121 return null;
3122 }
3123
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003124 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003125 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003126 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003127 }
3128
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003129 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003130 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3131 * and not available in ConnectivityManager.
3132 */
3133 @Override
3134 public VpnInfo[] getAllVpnInfo() {
3135 enforceConnectivityInternalPermission();
3136 if (mLockdownEnabled) {
3137 return new VpnInfo[0];
3138 }
3139
3140 synchronized(mVpns) {
3141 List<VpnInfo> infoList = new ArrayList<>();
3142 for (int i = 0; i < mVpns.size(); i++) {
3143 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3144 if (info != null) {
3145 infoList.add(info);
3146 }
3147 }
3148 return infoList.toArray(new VpnInfo[infoList.size()]);
3149 }
3150 }
3151
3152 /**
3153 * @return VPN information for accounting, or null if we can't retrieve all required
3154 * information, e.g primary underlying iface.
3155 */
3156 @Nullable
3157 private VpnInfo createVpnInfo(Vpn vpn) {
3158 VpnInfo info = vpn.getVpnInfo();
3159 if (info == null) {
3160 return null;
3161 }
3162 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3163 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3164 // the underlyingNetworks list.
3165 if (underlyingNetworks == null) {
3166 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3167 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3168 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3169 }
3170 } else if (underlyingNetworks.length > 0) {
3171 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3172 if (linkProperties != null) {
3173 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3174 }
3175 }
3176 return info.primaryUnderlyingIface == null ? null : info;
3177 }
3178
3179 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003180 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3181 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003182 * Permissions are checked in Vpn class.
3183 * @hide
3184 */
3185 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003186 public VpnConfig getVpnConfig(int userId) {
3187 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003188 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003189 Vpn vpn = mVpns.get(userId);
3190 if (vpn != null) {
3191 return vpn.getVpnConfig();
3192 } else {
3193 return null;
3194 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003195 }
3196 }
3197
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003198 @Override
3199 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003200 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3201 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3202 return false;
3203 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003204
3205 // Tear down existing lockdown if profile was removed
3206 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3207 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003208 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3209 final VpnProfile profile = VpnProfile.decode(
3210 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003211 if (profile == null) {
3212 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3213 setLockdownTracker(null);
3214 return true;
3215 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003216 int user = UserHandle.getUserId(Binder.getCallingUid());
3217 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003218 Vpn vpn = mVpns.get(user);
3219 if (vpn == null) {
3220 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3221 return false;
3222 }
3223 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003224 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003225 } else {
3226 setLockdownTracker(null);
3227 }
3228
3229 return true;
3230 }
3231
3232 /**
3233 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3234 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3235 */
3236 private void setLockdownTracker(LockdownVpnTracker tracker) {
3237 // Shutdown any existing tracker
3238 final LockdownVpnTracker existing = mLockdownTracker;
3239 mLockdownTracker = null;
3240 if (existing != null) {
3241 existing.shutdown();
3242 }
3243
3244 try {
3245 if (tracker != null) {
3246 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003247 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003248 mLockdownTracker = tracker;
3249 mLockdownTracker.init();
3250 } else {
3251 mNetd.setFirewallEnabled(false);
3252 }
3253 } catch (RemoteException e) {
3254 // ignored; NMS lives inside system_server
3255 }
3256 }
3257
3258 private void throwIfLockdownEnabled() {
3259 if (mLockdownEnabled) {
3260 throw new IllegalStateException("Unavailable in lockdown mode");
3261 }
3262 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003263
Robin Lee244ce8e2016-01-05 18:03:46 +00003264 /**
3265 * Sets up or tears down the always-on VPN for user {@param user} as appropriate.
3266 *
3267 * @return {@code false} in case of errors; {@code true} otherwise.
3268 */
3269 private boolean updateAlwaysOnVpn(int user) {
3270 final String lockdownPackage = getAlwaysOnVpnPackage(user);
3271 if (lockdownPackage == null) {
3272 return true;
3273 }
3274
3275 // Create an intent to start the VPN service declared in the app's manifest.
3276 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
3277 serviceIntent.setPackage(lockdownPackage);
3278
3279 try {
3280 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(user)) != null;
3281 } catch (RuntimeException e) {
3282 return false;
3283 }
3284 }
3285
3286 @Override
3287 public boolean setAlwaysOnVpnPackage(int userId, String packageName) {
3288 enforceConnectivityInternalPermission();
3289 enforceCrossUserPermission(userId);
3290
3291 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3292 if (LockdownVpnTracker.isEnabled()) {
3293 return false;
3294 }
3295
3296 // If the current VPN package is the same as the new one, this is a no-op
3297 final String oldPackage = getAlwaysOnVpnPackage(userId);
3298 if (TextUtils.equals(oldPackage, packageName)) {
3299 return true;
3300 }
3301
3302 synchronized (mVpns) {
3303 Vpn vpn = mVpns.get(userId);
3304 if (vpn == null) {
3305 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3306 return false;
3307 }
3308 if (!vpn.setAlwaysOnPackage(packageName)) {
3309 return false;
3310 }
3311 if (!updateAlwaysOnVpn(userId)) {
3312 vpn.setAlwaysOnPackage(null);
3313 return false;
3314 }
3315 }
3316 return true;
3317 }
3318
3319 @Override
3320 public String getAlwaysOnVpnPackage(int userId) {
3321 enforceConnectivityInternalPermission();
3322 enforceCrossUserPermission(userId);
3323
3324 synchronized (mVpns) {
3325 Vpn vpn = mVpns.get(userId);
3326 if (vpn == null) {
3327 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3328 return null;
3329 }
3330 return vpn.getAlwaysOnPackage();
3331 }
3332 }
3333
Wink Savilleab9321d2013-06-29 21:10:57 -07003334 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003335 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003336 // TODO: Remove? Any reason to trigger a provisioning check?
3337 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003338 }
3339
3340 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003341 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003342
Paul Jensen89e0f092014-09-15 15:59:36 -04003343 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003344 Intent intent = new Intent(action);
3345 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003346 // Concatenate the range of types onto the range of NetIDs.
3347 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003348 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003349 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003350 }
3351
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003352 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003353 * Show or hide network provisioning notifications.
3354 *
3355 * We use notifications for two purposes: to notify that a network requires sign in
3356 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3357 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3358 * particular network we can display the notification type that was most recently requested.
3359 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3360 * might first display NO_INTERNET, and then when the captive portal check completes, display
3361 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003362 *
3363 * @param id an identifier that uniquely identifies this notification. This must match
3364 * between show and hide calls. We use the NetID value but for legacy callers
3365 * we concatenate the range of types with the range of NetIDs.
3366 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003367 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003368 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3369 boolean highPriority) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003370 if (VDBG || (DBG && visible)) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003371 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3372 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003373 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003374 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003375
3376 Resources r = Resources.getSystem();
3377 NotificationManager notificationManager = (NotificationManager) mContext
3378 .getSystemService(Context.NOTIFICATION_SERVICE);
3379
3380 if (visible) {
3381 CharSequence title;
3382 CharSequence details;
3383 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003384 if (notifyType == NotificationType.NO_INTERNET &&
3385 networkType == ConnectivityManager.TYPE_WIFI) {
3386 title = r.getString(R.string.wifi_no_internet, 0);
3387 details = r.getString(R.string.wifi_no_internet_detailed);
3388 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3389 } else if (notifyType == NotificationType.SIGN_IN) {
3390 switch (networkType) {
3391 case ConnectivityManager.TYPE_WIFI:
3392 title = r.getString(R.string.wifi_available_sign_in, 0);
3393 details = r.getString(R.string.network_available_sign_in_detailed,
3394 extraInfo);
3395 icon = R.drawable.stat_notify_wifi_in_range;
3396 break;
3397 case ConnectivityManager.TYPE_MOBILE:
3398 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3399 title = r.getString(R.string.network_available_sign_in, 0);
3400 // TODO: Change this to pull from NetworkInfo once a printable
3401 // name has been added to it
3402 details = mTelephonyManager.getNetworkOperatorName();
3403 icon = R.drawable.stat_notify_rssi_in_range;
3404 break;
3405 default:
3406 title = r.getString(R.string.network_available_sign_in, 0);
3407 details = r.getString(R.string.network_available_sign_in_detailed,
3408 extraInfo);
3409 icon = R.drawable.stat_notify_rssi_in_range;
3410 break;
3411 }
3412 } else {
3413 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3414 + getNetworkTypeName(networkType));
3415 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003416 }
3417
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003418 Notification notification = new Notification.Builder(mContext)
3419 .setWhen(0)
3420 .setSmallIcon(icon)
3421 .setAutoCancel(true)
3422 .setTicker(title)
3423 .setColor(mContext.getColor(
3424 com.android.internal.R.color.system_notification_accent_color))
3425 .setContentTitle(title)
3426 .setContentText(details)
3427 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003428 .setLocalOnly(true)
3429 .setPriority(highPriority ?
3430 Notification.PRIORITY_HIGH :
3431 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003432 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003433 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003434 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003435
Wink Saville948282b2013-08-29 08:55:16 -07003436 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003437 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003438 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003439 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003440 npe.printStackTrace();
3441 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003442 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003443 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003444 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003445 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003446 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003447 npe.printStackTrace();
3448 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003449 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003450 }
3451
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003452 /** Location to an updatable file listing carrier provisioning urls.
3453 * An example:
3454 *
3455 * <?xml version="1.0" encoding="utf-8"?>
3456 * <provisioningUrls>
3457 * <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 -07003458 * </provisioningUrls>
3459 */
3460 private static final String PROVISIONING_URL_PATH =
3461 "/data/misc/radio/provisioning_urls.xml";
3462 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003463
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003464 /** XML tag for root element. */
3465 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3466 /** XML tag for individual url */
3467 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003468 /** XML attribute for mcc */
3469 private static final String ATTR_MCC = "mcc";
3470 /** XML attribute for mnc */
3471 private static final String ATTR_MNC = "mnc";
3472
Paul Jensen434dde82015-06-11 09:43:30 -04003473 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003474 FileReader fileReader = null;
3475 XmlPullParser parser = null;
3476 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003477
3478 try {
3479 fileReader = new FileReader(mProvisioningUrlFile);
3480 parser = Xml.newPullParser();
3481 parser.setInput(fileReader);
3482 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3483
3484 while (true) {
3485 XmlUtils.nextElement(parser);
3486
3487 String element = parser.getName();
3488 if (element == null) break;
3489
Paul Jensen434dde82015-06-11 09:43:30 -04003490 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003491 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3492 try {
3493 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3494 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3495 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3496 parser.next();
3497 if (parser.getEventType() == XmlPullParser.TEXT) {
3498 return parser.getText();
3499 }
3500 }
3501 }
3502 } catch (NumberFormatException e) {
3503 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3504 }
3505 }
3506 }
3507 return null;
3508 } catch (FileNotFoundException e) {
3509 loge("Carrier Provisioning Urls file not found");
3510 } catch (XmlPullParserException e) {
3511 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3512 } catch (IOException e) {
3513 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3514 } finally {
3515 if (fileReader != null) {
3516 try {
3517 fileReader.close();
3518 } catch (IOException e) {}
3519 }
3520 }
3521 return null;
3522 }
3523
Wink Saville42d4f082013-07-20 20:31:59 -07003524 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003525 public String getMobileProvisioningUrl() {
3526 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003527 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003528 if (TextUtils.isEmpty(url)) {
3529 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003530 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003531 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003532 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003533 }
Wink Saville8cf35602013-07-10 23:00:07 -07003534 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003535 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003536 String phoneNumber = mTelephonyManager.getLine1Number();
3537 if (TextUtils.isEmpty(phoneNumber)) {
3538 phoneNumber = "0000000000";
3539 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003540 url = String.format(url,
3541 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3542 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003543 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003544 }
3545
Wink Savilleab9321d2013-06-29 21:10:57 -07003546 return url;
3547 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003548
Wink Saville948282b2013-08-29 08:55:16 -07003549 @Override
3550 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003551 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003552 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003553 final long ident = Binder.clearCallingIdentity();
3554 try {
3555 setProvNotificationVisible(visible, networkType, action);
3556 } finally {
3557 Binder.restoreCallingIdentity(ident);
3558 }
Wink Saville948282b2013-08-29 08:55:16 -07003559 }
Wink Saville7788c612013-08-29 14:57:08 -07003560
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003561 @Override
3562 public void setAirplaneMode(boolean enable) {
3563 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003564 final long ident = Binder.clearCallingIdentity();
3565 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003566 final ContentResolver cr = mContext.getContentResolver();
3567 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3568 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3569 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003570 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003571 } finally {
3572 Binder.restoreCallingIdentity(ident);
3573 }
3574 }
3575
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003576 private void onUserStart(int userId) {
3577 synchronized(mVpns) {
3578 Vpn userVpn = mVpns.get(userId);
3579 if (userVpn != null) {
3580 loge("Starting user already has a VPN");
3581 return;
3582 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003583 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003584 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003585 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003586 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3587 updateLockdownVpn();
3588 } else {
3589 updateAlwaysOnVpn(userId);
3590 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003591 }
3592
3593 private void onUserStop(int userId) {
3594 synchronized(mVpns) {
3595 Vpn userVpn = mVpns.get(userId);
3596 if (userVpn == null) {
3597 loge("Stopping user has no VPN");
3598 return;
3599 }
3600 mVpns.delete(userId);
3601 }
3602 }
3603
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003604 private void onUserAdded(int userId) {
3605 synchronized(mVpns) {
3606 final int vpnsSize = mVpns.size();
3607 for (int i = 0; i < vpnsSize; i++) {
3608 Vpn vpn = mVpns.valueAt(i);
3609 vpn.onUserAdded(userId);
3610 }
3611 }
3612 }
3613
3614 private void onUserRemoved(int userId) {
3615 synchronized(mVpns) {
3616 final int vpnsSize = mVpns.size();
3617 for (int i = 0; i < vpnsSize; i++) {
3618 Vpn vpn = mVpns.valueAt(i);
3619 vpn.onUserRemoved(userId);
3620 }
3621 }
3622 }
3623
Robin Lee89e7a692016-02-29 14:38:17 +00003624 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003625 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3626 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3627 updateLockdownVpn();
3628 } else {
3629 updateAlwaysOnVpn(userId);
3630 }
3631 }
3632
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003633 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3634 @Override
3635 public void onReceive(Context context, Intent intent) {
3636 final String action = intent.getAction();
3637 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3638 if (userId == UserHandle.USER_NULL) return;
3639
3640 if (Intent.ACTION_USER_STARTING.equals(action)) {
3641 onUserStart(userId);
3642 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3643 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003644 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3645 onUserAdded(userId);
3646 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3647 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003648 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3649 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003650 }
3651 }
3652 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003653
Robert Greenwalta67be032014-05-16 15:49:14 -07003654 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3655 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003656 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3657 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003658
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003659 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3660 // Map from UID to number of NetworkRequests that UID has filed.
3661 @GuardedBy("mUidToNetworkRequestCount")
3662 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3663
Robert Greenwalta67be032014-05-16 15:49:14 -07003664 private static class NetworkFactoryInfo {
3665 public final String name;
3666 public final Messenger messenger;
3667 public final AsyncChannel asyncChannel;
3668
3669 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3670 this.name = name;
3671 this.messenger = messenger;
3672 this.asyncChannel = asyncChannel;
3673 }
3674 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003675
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003676 /**
Erik Kline371c7b72016-03-22 17:04:20 +09003677 * A NetworkRequest as registered by an application can be one of three
3678 * types:
3679 *
3680 * - "listen", for which the framework will issue callbacks about any
3681 * and all networks that match the specified NetworkCapabilities,
3682 *
3683 * - "request", capable of causing a specific network to be created
3684 * first (e.g. a telephony DUN request), the framework will issue
3685 * callbacks about the single, highest scoring current network
3686 * (if any) that matches the specified NetworkCapabilities, or
3687 *
3688 * - "track the default network", a hybrid of the two designed such
3689 * that the framework will issue callbacks for the single, highest
3690 * scoring current network (if any) that matches the capabilities of
3691 * the default Internet request (mDefaultRequest), but which cannot
3692 * cause the framework to either create or retain the existence of
3693 * any specific network.
3694 *
3695 */
3696 private static enum NetworkRequestType {
3697 LISTEN,
3698 TRACK_DEFAULT,
3699 REQUEST
3700 };
3701
3702 /**
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003703 * Tracks info about the requester.
3704 * Also used to notice when the calling process dies so we can self-expire
3705 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003706 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003707 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003708 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003709 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003710 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003711 final int mPid;
3712 final int mUid;
3713 final Messenger messenger;
Erik Kline371c7b72016-03-22 17:04:20 +09003714 private final NetworkRequestType mType;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003715
Erik Kline371c7b72016-03-22 17:04:20 +09003716 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003717 request = r;
3718 mPendingIntent = pi;
3719 messenger = null;
3720 mBinder = null;
3721 mPid = getCallingPid();
3722 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003723 mType = type;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003724 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003725 }
3726
Erik Kline371c7b72016-03-22 17:04:20 +09003727 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003728 super();
3729 messenger = m;
3730 request = r;
3731 mBinder = binder;
3732 mPid = getCallingPid();
3733 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003734 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003735 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003736 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003737
3738 try {
3739 mBinder.linkToDeath(this, 0);
3740 } catch (RemoteException e) {
3741 binderDied();
3742 }
3743 }
3744
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003745 private void enforceRequestCountLimit() {
3746 synchronized (mUidToNetworkRequestCount) {
3747 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3748 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3749 throw new IllegalArgumentException("Too many NetworkRequests filed");
3750 }
3751 mUidToNetworkRequestCount.put(mUid, networkRequests);
3752 }
3753 }
3754
Erik Kline371c7b72016-03-22 17:04:20 +09003755 private String typeString() {
3756 switch (mType) {
3757 case LISTEN: return "Listen";
3758 case REQUEST: return "Request";
3759 case TRACK_DEFAULT: return "Track default";
3760 default:
3761 return "unknown type";
3762 }
3763 }
3764
Robert Greenwalt9258c642014-03-26 16:47:06 -07003765 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003766 if (mBinder != null) {
3767 mBinder.unlinkToDeath(this, 0);
3768 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003769 }
3770
3771 public void binderDied() {
3772 log("ConnectivityService NetworkRequestInfo binderDied(" +
3773 request + ", " + mBinder + ")");
3774 releaseNetworkRequest(request);
3775 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003776
Erik Kline371c7b72016-03-22 17:04:20 +09003777 /**
3778 * Returns true iff. the contained NetworkRequest is one that:
3779 *
3780 * - should be associated with at most one satisfying network
3781 * at a time;
3782 *
3783 * - should cause a network to be kept up if it is the only network
3784 * which can satisfy the NetworkReqeust.
3785 *
3786 * For full detail of how isRequest() is used for pairing Networks with
3787 * NetworkRequests read rematchNetworkAndRequests().
3788 *
3789 * TODO: Rename to something more properly descriptive.
3790 */
3791 public boolean isRequest() {
3792 return (mType == NetworkRequestType.TRACK_DEFAULT) ||
3793 (mType == NetworkRequestType.REQUEST);
3794 }
3795
Robert Greenwalta67be032014-05-16 15:49:14 -07003796 public String toString() {
Erik Kline371c7b72016-03-22 17:04:20 +09003797 return typeString() +
Erik Kline7523eb32015-07-09 18:24:03 +09003798 " from uid/pid:" + mUid + "/" + mPid +
3799 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003800 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003801 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003802 }
3803
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003804 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3805 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3806 if (badCapability != null) {
3807 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003808 }
3809 }
3810
Erik Kline9d598e12015-07-13 16:37:51 +09003811 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003812 final SortedSet<Integer> thresholds = new TreeSet();
3813 synchronized (nai) {
3814 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3815 if (nri.request.networkCapabilities.hasSignalStrength() &&
3816 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3817 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3818 }
3819 }
3820 }
Erik Kline9d598e12015-07-13 16:37:51 +09003821 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003822 }
3823
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003824 private void updateSignalStrengthThresholds(
3825 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3826 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003827 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003828 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3829
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003830 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003831 String detail;
3832 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3833 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3834 } else {
3835 detail = reason;
3836 }
3837 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3838 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3839 }
3840
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003841 nai.asyncChannel.sendMessage(
3842 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003843 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003844 }
3845
Robert Greenwalt9258c642014-03-26 16:47:06 -07003846 @Override
3847 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003848 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Erik Kline371c7b72016-03-22 17:04:20 +09003849 final NetworkRequestType type = (networkCapabilities == null)
3850 ? NetworkRequestType.TRACK_DEFAULT
3851 : NetworkRequestType.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09003852 // If the requested networkCapabilities is null, take them instead from
3853 // the default network request. This allows callers to keep track of
3854 // the system default network.
Erik Kline371c7b72016-03-22 17:04:20 +09003855 if (type == NetworkRequestType.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09003856 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3857 enforceAccessPermission();
3858 } else {
3859 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3860 enforceNetworkRequestPermissions(networkCapabilities);
3861 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003862 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003863 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003864
Robert Greenwalt6078b502014-06-11 16:05:07 -07003865 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003866 throw new IllegalArgumentException("Bad timeout specified");
3867 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003868
Etan Cohenddb9ef02015-11-18 10:56:15 -08003869 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
3870 .equals(networkCapabilities.getNetworkSpecifier())) {
3871 throw new IllegalArgumentException("Invalid network specifier - must not be '"
3872 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
3873 }
3874
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003875 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3876 nextNetworkRequestId());
Erik Kline371c7b72016-03-22 17:04:20 +09003877 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type);
Erik Kline7523eb32015-07-09 18:24:03 +09003878 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003879
3880 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003881 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003882 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003883 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003884 }
3885 return networkRequest;
3886 }
3887
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003888 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003889 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003890 enforceConnectivityInternalPermission();
3891 } else {
3892 enforceChangePermission();
3893 }
3894 }
3895
fenglub15e72b2015-03-20 11:29:56 -07003896 @Override
fengludb571472015-04-21 17:12:05 -07003897 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003898 enforceAccessPermission();
3899 NetworkAgentInfo nai = null;
3900 if (network == null) {
3901 return false;
3902 }
3903 synchronized (mNetworkForNetId) {
3904 nai = mNetworkForNetId.get(network.netId);
3905 }
3906 if (nai != null) {
3907 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3908 return true;
3909 }
3910 return false;
3911 }
3912
3913
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003914 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3915 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003916 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003917 final int uidRules;
3918 final int uid = Binder.getCallingUid();
3919 synchronized(mRulesLock) {
3920 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3921 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003922 if (uidRules != RULE_ALLOW_ALL) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003923 // we could silently fail or we can filter the available nets to only give
3924 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003925 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003926 }
3927 }
3928 }
3929
Robert Greenwalt9258c642014-03-26 16:47:06 -07003930 @Override
3931 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3932 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003933 checkNotNull(operation, "PendingIntent cannot be null.");
3934 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3935 enforceNetworkRequestPermissions(networkCapabilities);
3936 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003937 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003938
3939 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3940 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003941 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09003942 NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003943 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003944 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3945 nri));
3946 return networkRequest;
3947 }
3948
Jeremy Joslin79294842014-12-03 17:15:28 -08003949 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3950 mHandler.sendMessageDelayed(
3951 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3952 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3953 }
3954
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003955 @Override
3956 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003957 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003958 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3959 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003960 }
3961
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003962 // In order to implement the compatibility measure for pre-M apps that call
3963 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3964 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3965 // This ensures it has permission to do so.
3966 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3967 if (nc == null) {
3968 return false;
3969 }
3970 int[] transportTypes = nc.getTransportTypes();
3971 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3972 return false;
3973 }
3974 try {
3975 mContext.enforceCallingOrSelfPermission(
3976 android.Manifest.permission.ACCESS_WIFI_STATE,
3977 "ConnectivityService");
3978 } catch (SecurityException e) {
3979 return false;
3980 }
3981 return true;
3982 }
3983
Robert Greenwalt9258c642014-03-26 16:47:06 -07003984 @Override
3985 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3986 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003987 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3988 enforceAccessPermission();
3989 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003990
Erik Kline7523eb32015-07-09 18:24:03 +09003991 NetworkRequest networkRequest = new NetworkRequest(
3992 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003993 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
Erik Kline371c7b72016-03-22 17:04:20 +09003994 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003995 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003996
3997 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3998 return networkRequest;
3999 }
4000
4001 @Override
4002 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4003 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004004 checkNotNull(operation, "PendingIntent cannot be null.");
4005 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4006 enforceAccessPermission();
4007 }
4008
Erik Kline7523eb32015-07-09 18:24:03 +09004009 NetworkRequest networkRequest = new NetworkRequest(
4010 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04004011 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004012 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004013 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004014
4015 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004016 }
4017
4018 @Override
4019 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04004020 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4021 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004022 }
4023
4024 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004025 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004026 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004027 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4028 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004029 }
4030
Robert Greenwalta67be032014-05-16 15:49:14 -07004031 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004032 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004033 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4034 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4035 }
4036
4037 @Override
4038 public void unregisterNetworkFactory(Messenger messenger) {
4039 enforceConnectivityInternalPermission();
4040 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4041 }
4042
4043 private void handleUnregisterNetworkFactory(Messenger messenger) {
4044 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4045 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004046 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004047 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004048 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004049 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004050 }
4051
Robert Greenwalt7b816022014-04-18 15:25:25 -07004052 /**
4053 * NetworkAgentInfo supporting a request by requestId.
4054 * These have already been vetted (their Capabilities satisfy the request)
4055 * and the are the highest scored network available.
4056 * the are keyed off the Requests requestId.
4057 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004058 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004059 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4060 new SparseArray<NetworkAgentInfo>();
4061
Paul Jensen31a94f42015-02-13 14:18:39 -05004062 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4063 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004064 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4065 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004066 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4067 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4068 // there may not be a strict 1:1 correlation between the two.
4069 @GuardedBy("mNetworkForNetId")
4070 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004071
Robert Greenwalt7b816022014-04-18 15:25:25 -07004072 // NetworkAgentInfo keyed off its connecting messenger
4073 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004074 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004075 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4076 new HashMap<Messenger, NetworkAgentInfo>();
4077
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004078 @GuardedBy("mBlockedAppUids")
4079 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4080
Paul Jensen2c311d62014-11-17 12:34:51 -05004081 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004082 private final NetworkRequest mDefaultRequest;
4083
Erik Klineda4bfa82015-04-30 12:58:40 +09004084 // Request used to optionally keep mobile data active even when higher
4085 // priority networks like Wi-Fi are active.
4086 private final NetworkRequest mDefaultMobileDataRequest;
4087
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004088 private NetworkAgentInfo getDefaultNetwork() {
4089 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4090 }
4091
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004092 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004093 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004094 }
4095
Paul Jensen31a94f42015-02-13 14:18:39 -05004096 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004097 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004098 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004099 enforceConnectivityInternalPermission();
4100
Paul Jensen2c311d62014-11-17 12:34:51 -05004101 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4102 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004103 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004104 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4105 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004106 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004107 synchronized (this) {
4108 nai.networkMonitor.systemReady = mSystemReady;
4109 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07004110 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004111 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004112 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004113 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004114 }
4115
4116 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4117 if (VDBG) log("Got NetworkAgent Messenger");
4118 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004119 synchronized (mNetworkForNetId) {
4120 mNetworkForNetId.put(na.network.netId, na);
4121 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004122 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4123 NetworkInfo networkInfo = na.networkInfo;
4124 na.networkInfo = null;
4125 updateNetworkInfo(na, networkInfo);
4126 }
4127
4128 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4129 LinkProperties newLp = networkAgent.linkProperties;
4130 int netId = networkAgent.network.netId;
4131
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004132 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4133 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004134 if (networkAgent.clatd != null) {
4135 networkAgent.clatd.fixupLinkProperties(oldLp);
4136 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004137
Paul Jensen992f2522014-04-28 10:33:11 -04004138 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004139 updateMtu(newLp, oldLp);
4140 // TODO - figure out what to do for clat
4141// for (LinkProperties lp : newLp.getStackedLinks()) {
4142// updateMtu(lp, null);
4143// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004144 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004145
Erik Kline94887872016-04-05 13:30:49 +09004146 updateRoutes(newLp, oldLp, netId);
4147 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004148
Paul Jensen3b759822014-05-13 11:44:01 -04004149 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004150 if (isDefaultNetwork(networkAgent)) {
4151 handleApplyDefaultProxy(newLp.getHttpProxy());
4152 } else {
4153 updateProxy(newLp, oldLp, networkAgent);
4154 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004155 // TODO - move this check to cover the whole function
4156 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004157 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004158 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4159 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004160
4161 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004162 }
4163
Lorenzo Colitti95439462014-10-09 13:44:48 +09004164 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4165 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4166 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004167
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004168 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004169 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4170 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004171 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004172 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004173 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004174 }
Paul Jensen992f2522014-04-28 10:33:11 -04004175
4176 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4177 CompareResult<String> interfaceDiff = new CompareResult<String>();
4178 if (oldLp != null) {
4179 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4180 } else if (newLp != null) {
4181 interfaceDiff.added = newLp.getAllInterfaceNames();
4182 }
4183 for (String iface : interfaceDiff.added) {
4184 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004185 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004186 mNetd.addInterfaceToNetwork(iface, netId);
4187 } catch (Exception e) {
4188 loge("Exception adding interface: " + e);
4189 }
4190 }
4191 for (String iface : interfaceDiff.removed) {
4192 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004193 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004194 mNetd.removeInterfaceFromNetwork(iface, netId);
4195 } catch (Exception e) {
4196 loge("Exception removing interface: " + e);
4197 }
4198 }
4199 }
4200
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004201 /**
4202 * Have netd update routes from oldLp to newLp.
4203 * @return true if routes changed between oldLp and newLp
4204 */
4205 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004206 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4207 if (oldLp != null) {
4208 routeDiff = oldLp.compareAllRoutes(newLp);
4209 } else if (newLp != null) {
4210 routeDiff.added = newLp.getAllRoutes();
4211 }
4212
4213 // add routes before removing old in case it helps with continuous connectivity
4214
4215 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4216 for (RouteInfo route : routeDiff.added) {
4217 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004218 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004219 try {
4220 mNetd.addRoute(netId, route);
4221 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004222 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4223 loge("Exception in addRoute for non-gateway: " + e);
4224 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004225 }
4226 }
4227 for (RouteInfo route : routeDiff.added) {
4228 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004229 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004230 try {
4231 mNetd.addRoute(netId, route);
4232 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004233 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4234 loge("Exception in addRoute for gateway: " + e);
4235 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004236 }
4237 }
4238
4239 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004240 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004241 try {
4242 mNetd.removeRoute(netId, route);
4243 } catch (Exception e) {
4244 loge("Exception in removeRoute: " + e);
4245 }
4246 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004247 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004248 }
Erik Kline41368502015-06-17 13:19:54 +09004249
Erik Kline94887872016-04-05 13:30:49 +09004250 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4251 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4252 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004253 }
Erik Kline94887872016-04-05 13:30:49 +09004254
4255 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004256 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004257 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004258 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004259 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4260 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004261 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004262 }
4263 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4264 if (defaultNai != null && defaultNai.network.netId == netId) {
4265 setDefaultDnsSystemProperties(dnses);
4266 }
4267 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004268 }
4269
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004270 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4271 int last = 0;
4272 for (InetAddress dns : dnses) {
4273 ++last;
4274 String key = "net.dns" + last;
4275 String value = dns.getHostAddress();
4276 SystemProperties.set(key, value);
4277 }
4278 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4279 String key = "net.dns" + i;
4280 SystemProperties.set(key, "");
4281 }
4282 mNumDnsEntries = last;
4283 }
4284
Paul Jensen3d194ea2015-06-16 14:27:36 -04004285 /**
4286 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4287 * augmented with any stateful capabilities implied from {@code networkAgent}
4288 * (e.g., validated status and captive portal status).
4289 *
Paul Jensene0988542015-06-25 15:30:08 -04004290 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004291 * @param networkCapabilities the new network capabilities.
4292 */
Paul Jensene0988542015-06-25 15:30:08 -04004293 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004294 // Don't modify caller's NetworkCapabilities.
4295 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004296 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004297 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4298 } else {
4299 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4300 }
Paul Jensene0988542015-06-25 15:30:08 -04004301 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004302 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4303 } else {
4304 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4305 }
Paul Jensene0988542015-06-25 15:30:08 -04004306 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4307 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004308 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4309 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4310 try {
4311 mNetd.setNetworkPermission(nai.network.netId,
4312 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4313 null : NetworkManagementService.PERMISSION_SYSTEM);
4314 } catch (RemoteException e) {
4315 loge("Exception in setNetworkPermission: " + e);
4316 }
4317 }
Paul Jensene0988542015-06-25 15:30:08 -04004318 synchronized (nai) {
4319 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004320 }
Paul Jensene0988542015-06-25 15:30:08 -04004321 rematchAllNetworksAndRequests(nai, oldScore);
4322 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004323 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004324 }
4325
Paul Jensenc8b9a742014-09-30 15:37:41 -04004326 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4327 for (int i = 0; i < nai.networkRequests.size(); i++) {
4328 NetworkRequest nr = nai.networkRequests.valueAt(i);
4329 // Don't send listening requests to factories. b/17393458
4330 if (!isRequest(nr)) continue;
4331 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4332 }
4333 }
4334
Robert Greenwalt7b816022014-04-18 15:25:25 -07004335 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4336 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004337 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004338 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4339 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004340 }
4341 }
4342
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004343 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4344 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004345 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004346 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004347 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4348 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004349 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004350 sendIntent(nri.mPendingIntent, intent);
4351 }
4352 // else not handled
4353 }
4354
4355 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4356 mPendingIntentWakeLock.acquire();
4357 try {
4358 if (DBG) log("Sending " + pendingIntent);
4359 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4360 } catch (PendingIntent.CanceledException e) {
4361 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4362 mPendingIntentWakeLock.release();
4363 releasePendingNetworkRequest(pendingIntent);
4364 }
4365 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4366 }
4367
4368 @Override
4369 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4370 String resultData, Bundle resultExtras) {
4371 if (DBG) log("Finished sending " + pendingIntent);
4372 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004373 // Release with a delay so the receiving client has an opportunity to put in its
4374 // own request.
4375 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004376 }
4377
Robert Greenwalt9258c642014-03-26 16:47:06 -07004378 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004379 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004380 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004381 Bundle bundle = new Bundle();
4382 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4383 new NetworkRequest(nri.request));
4384 Message msg = Message.obtain();
4385 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4386 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4387 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4388 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004389 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004390 case ConnectivityManager.CALLBACK_LOSING: {
4391 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4392 break;
4393 }
4394 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4395 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4396 new NetworkCapabilities(networkAgent.networkCapabilities));
4397 break;
4398 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004399 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004400 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4401 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004402 break;
4403 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004404 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004405 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004406 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004407 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004408 if (VDBG) {
4409 log("sending notification " + notifyTypeToName(notificationType) +
4410 " for " + nri.request);
4411 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004412 nri.messenger.send(msg);
4413 } catch (RemoteException e) {
4414 // may occur naturally in the race of binder death.
4415 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4416 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004417 }
4418
Paul Jensenc8b9a742014-09-30 15:37:41 -04004419 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4420 for (int i = 0; i < nai.networkRequests.size(); i++) {
4421 NetworkRequest nr = nai.networkRequests.valueAt(i);
4422 // Ignore listening requests.
4423 if (!isRequest(nr)) continue;
4424 loge("Dead network still had at least " + nr);
4425 break;
4426 }
4427 nai.asyncChannel.disconnect();
4428 }
4429
Robert Greenwalt7b816022014-04-18 15:25:25 -07004430 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4431 if (oldNetwork == null) {
4432 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4433 return;
4434 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004435 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4436 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004437 }
4438
Pierre Imai6b4e15b2016-04-07 12:21:05 +09004439 private void makeDefault(NetworkAgentInfo newNetwork, NetworkAgentInfo prevNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004440 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004441 setupDataActivityTracking(newNetwork);
4442 try {
4443 mNetd.setDefaultNetId(newNetwork.network.netId);
4444 } catch (Exception e) {
4445 loge("Exception setting default network :" + e);
4446 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004447 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004448 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004449 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004450 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Hugo Benichi5f16f762016-04-20 12:09:33 +09004451 logDefaultNetworkEvent(newNetwork, prevNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004452 }
4453
Paul Jensen2161a8e2014-09-11 11:00:39 -04004454 // Handles a network appearing or improving its score.
4455 //
4456 // - Evaluates all current NetworkRequests that can be
4457 // satisfied by newNetwork, and reassigns to newNetwork
4458 // any such requests for which newNetwork is the best.
4459 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004460 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004461 // needed. A network is needed if it is the best network for
4462 // one or more NetworkRequests, or if it is a VPN.
4463 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004464 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004465 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004466 //
4467 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4468 // networks that have no chance (i.e. even if validated)
4469 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004470 //
4471 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4472 // it does not remove NetworkRequests that other Networks could better satisfy.
4473 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4474 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4475 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004476 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004477 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004478 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4479 // performed to tear down unvalidated networks that have no chance (i.e. even if
4480 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004481 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004482 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004483 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004484 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004485 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004486 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004487 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004488 // Find and migrate to this Network any NetworkRequests for
4489 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004490 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004491 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004492 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004493 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004494 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4495 final boolean satisfies = newNetwork.satisfies(nri.request);
4496 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004497 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004498 log("Network " + newNetwork.name() + " was already satisfying" +
4499 " request " + nri.request.requestId + ". No change.");
4500 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004501 keep = true;
4502 continue;
4503 }
4504
4505 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004506 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004507 if (satisfies) {
Erik Kline371c7b72016-03-22 17:04:20 +09004508 if (!nri.isRequest()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004509 // This is not a request, it's a callback listener.
4510 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004511 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004512 continue;
4513 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004514
Robert Greenwalt7b816022014-04-18 15:25:25 -07004515 // next check if it's better than any current network we're using for
4516 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004517 if (VDBG) {
4518 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004519 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4520 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004521 }
4522 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004523 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004524 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004525 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004526 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004527 currentNetwork.networkRequests.remove(nri.request.requestId);
4528 currentNetwork.networkLingered.add(nri.request);
4529 affectedNetworks.add(currentNetwork);
4530 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004531 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004532 }
Paul Jensen573a0352015-01-08 10:49:34 -05004533 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004534 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004535 if (!newNetwork.addRequest(nri.request)) {
4536 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4537 }
4538 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004539 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004540 // Tell NetworkFactories about the new score, so they can stop
4541 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004542 // TODO - this could get expensive if we have alot of requests for this
4543 // network. Think about if there is a way to reduce this. Push
4544 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004545 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004546 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004547 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004548 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004549 }
4550 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004551 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4552 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4553 // mark it as no longer satisfying "nri". Because networks are processed by
4554 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4555 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4556 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4557 // This means this code doesn't have to handle the case where "currentNetwork" no
4558 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4559 if (DBG) {
4560 log("Network " + newNetwork.name() + " stopped satisfying" +
4561 " request " + nri.request.requestId);
4562 }
4563 newNetwork.networkRequests.remove(nri.request.requestId);
4564 if (currentNetwork == newNetwork) {
4565 mNetworkForRequestId.remove(nri.request.requestId);
4566 sendUpdatedScoreToFactories(nri.request, 0);
4567 } else {
Erik Kline371c7b72016-03-22 17:04:20 +09004568 if (nri.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004569 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4570 newNetwork.name() +
4571 " without updating mNetworkForRequestId or factories!");
4572 }
4573 }
4574 // TODO: technically, sending CALLBACK_LOST here is
4575 // incorrect if nri is a request (not a listen) and there
4576 // is a replacement network currently connected that can
4577 // satisfy it. However, the only capability that can both
4578 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4579 // so this code is only incorrect for a network that loses
4580 // the TRUSTED capability, which is a rare case.
4581 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004582 }
4583 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004584 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004585 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004586 if (nai.lingering) {
4587 // Already lingered. Nothing to do. This can only happen if "nai" is in
4588 // "affectedNetworks" twice. The reasoning being that to get added to
4589 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4590 // (i.e. not lingered) so it could have only been lingered by this loop.
4591 // unneeded(nai) will be false and we'll call unlinger() below which would
4592 // be bad, so handle it here.
4593 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004594 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004595 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004596 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004597 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004598 }
4599 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004600 if (isNewDefault) {
4601 // Notify system services that this network is up.
Pierre Imai6b4e15b2016-04-07 12:21:05 +09004602 makeDefault(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004603 synchronized (ConnectivityService.this) {
4604 // have a new default network, release the transition wakelock in
4605 // a second if it's held. The second pause is to allow apps
4606 // to reconnect over the new network
4607 if (mNetTransitionWakeLock.isHeld()) {
4608 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4609 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4610 mNetTransitionWakeLockSerialNumber, 0),
4611 1000);
4612 }
4613 }
4614 }
4615
4616 // do this after the default net is switched, but
4617 // before LegacyTypeTracker sends legacy broadcasts
4618 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4619
4620 if (isNewDefault) {
4621 // Maintain the illusion: since the legacy API only
4622 // understands one network at a time, we must pretend
4623 // that the current default network disconnected before
4624 // the new one connected.
4625 if (oldDefaultNetwork != null) {
4626 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4627 oldDefaultNetwork, true);
4628 }
4629 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4630 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4631 notifyLockdownVpn(newNetwork);
4632 }
4633
Robert Greenwalt7b816022014-04-18 15:25:25 -07004634 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004635 // Notify battery stats service about this network, both the normal
4636 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004637 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004638 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004639 final IBatteryStats bs = BatteryStatsService.getService();
4640 final int type = newNetwork.networkInfo.getType();
4641
4642 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4643 bs.noteNetworkInterfaceType(baseIface, type);
4644 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4645 final String stackedIface = stacked.getInterfaceName();
4646 bs.noteNetworkInterfaceType(stackedIface, type);
4647 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4648 }
4649 } catch (RemoteException ignored) {
4650 }
4651
Robert Greenwalt152ed372014-12-17 17:19:53 -08004652 // This has to happen after the notifyNetworkCallbacks as that tickles each
4653 // ConnectivityManager instance so that legacy requests correctly bind dns
4654 // requests to this network. The legacy users are listening for this bcast
4655 // and will generally do a dns request so they can ensureRouteToHost and if
4656 // they do that before the callbacks happen they'll use the default network.
4657 //
4658 // TODO: Is there still a race here? We send the broadcast
4659 // after sending the callback, but if the app can receive the
4660 // broadcast before the callback, it might still break.
4661 //
4662 // This *does* introduce a race where if the user uses the new api
4663 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4664 // they may get old info. Reverse this after the old startUsing api is removed.
4665 // This is on top of the multiple intent sequencing referenced in the todo above.
4666 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4667 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4668 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4669 // legacy type tracker filters out repeat adds
4670 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4671 }
4672 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004673
4674 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4675 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4676 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4677 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4678 if (newNetwork.isVPN()) {
4679 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4680 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004681 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004682 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4683 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004684 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004685 if (DBG) log("Reaping " + nai.name());
4686 teardownUnneededNetwork(nai);
4687 }
4688 }
4689 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004690 }
4691
Paul Jensen1c7ba022015-06-16 14:27:36 -04004692 /**
4693 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4694 * being disconnected.
4695 * @param changed If only one Network's score or capabilities have been modified since the last
4696 * time this function was called, pass this Network in this argument, otherwise pass
4697 * null.
4698 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4699 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4700 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4701 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4702 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004703 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004704 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004705 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4706 // to avoid the slowness. It is not simply enough to process just "changed", for
4707 // example in the case where "changed"'s score decreases and another network should begin
4708 // satifying a NetworkRequest that "changed" currently satisfies.
4709
4710 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4711 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4712 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004713 if (changed != null && oldScore < changed.getCurrentScore()) {
4714 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004715 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004716 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4717 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4718 // Rematch higher scoring networks first to prevent requests first matching a lower
4719 // scoring network and then a higher scoring network, which could produce multiple
4720 // callbacks and inadvertently unlinger networks.
4721 Arrays.sort(nais);
4722 for (NetworkAgentInfo nai : nais) {
4723 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004724 // Only reap the last time through the loop. Reaping before all rematching
4725 // is complete could incorrectly teardown a network that hasn't yet been
4726 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004727 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004728 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004729 }
4730 }
4731 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004732
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004733 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004734 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004735 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004736 // For now only update icons for default connection.
4737 // TODO: Update WiFi and cellular icons separately. b/17237507
4738 if (!isDefaultNetwork(nai)) return;
4739
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004740 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004741 // Don't repeat publish.
4742 if (newInetCondition == mDefaultInetConditionPublished) return;
4743
4744 mDefaultInetConditionPublished = newInetCondition;
4745 sendInetConditionBroadcast(nai.networkInfo);
4746 }
4747
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004748 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4749 if (mLockdownTracker != null) {
4750 if (nai != null && nai.isVPN()) {
4751 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4752 } else {
4753 mLockdownTracker.onNetworkInfoChanged();
4754 }
4755 }
4756 }
4757
Robert Greenwalt7b816022014-04-18 15:25:25 -07004758 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4759 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004760 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004761 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004762 synchronized (networkAgent) {
4763 oldInfo = networkAgent.networkInfo;
4764 networkAgent.networkInfo = newInfo;
4765 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004766 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004767
4768 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004769 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4770 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4771 notifyIfacesChangedForNetworkStats();
4772 } else if (VDBG) log("ignoring duplicate network state non-change");
4773 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004774 return;
4775 }
4776 if (DBG) {
4777 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4778 (oldInfo == null ? "null" : oldInfo.getState()) +
4779 " to " + state);
4780 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004781
Paul Jenseneec75412014-08-04 12:21:19 -04004782 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004783 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004784 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004785 if (networkAgent.isVPN()) {
4786 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004787 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4788 (networkAgent.networkMisc == null ||
4789 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004790 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004791 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4792 networkAgent.networkCapabilities.hasCapability(
4793 NET_CAPABILITY_NOT_RESTRICTED) ?
4794 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004795 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004796 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004797 loge("Error creating network " + networkAgent.network.netId + ": "
4798 + e.getMessage());
4799 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004800 }
Paul Jenseneec75412014-08-04 12:21:19 -04004801 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004802 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004803 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004804
Paul Jensenca8f16a2014-05-09 12:47:55 -04004805 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004806 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004807
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004808 if (networkAgent.isVPN()) {
4809 // Temporarily disable the default proxy (not global).
4810 synchronized (mProxyLock) {
4811 if (!mDefaultProxyDisabled) {
4812 mDefaultProxyDisabled = true;
4813 if (mGlobalProxy == null && mDefaultProxy != null) {
4814 sendProxyBroadcast(null);
4815 }
4816 }
4817 }
4818 // TODO: support proxy per network.
4819 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004820
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004821 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4822 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4823 // capabilities, so it only needs to be done once on initial connect, not every time the
4824 // network's capabilities change. Note that we do this before rematching the network,
4825 // so we could decide to tear it down immediately afterwards. That's fine though - on
4826 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4827 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004828 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004829
Paul Jensen2161a8e2014-09-11 11:00:39 -04004830 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004831 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004832
4833 // This has to happen after matching the requests, because callbacks are just requests.
4834 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004835 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004836 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004837 if (networkAgent.isVPN()) {
4838 synchronized (mProxyLock) {
4839 if (mDefaultProxyDisabled) {
4840 mDefaultProxyDisabled = false;
4841 if (mGlobalProxy == null && mDefaultProxy != null) {
4842 sendProxyBroadcast(mDefaultProxy);
4843 }
4844 }
4845 }
4846 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004847 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4848 state == NetworkInfo.State.SUSPENDED) {
4849 // going into or coming out of SUSPEND: rescore and notify
4850 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004851 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004852 }
4853 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4854 ConnectivityManager.CALLBACK_SUSPENDED :
4855 ConnectivityManager.CALLBACK_RESUMED));
4856 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004857 }
4858 }
4859
Robert Greenwaltac96c522014-06-03 16:43:57 -07004860 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004861 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004862 if (score < 0) {
4863 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4864 "). Bumping score to min of 0");
4865 score = 0;
4866 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004867
Paul Jensen2161a8e2014-09-11 11:00:39 -04004868 final int oldScore = nai.getCurrentScore();
4869 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004870
Paul Jensen85cf78e2015-06-25 13:25:07 -04004871 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004872
Paul Jensenc8b9a742014-09-30 15:37:41 -04004873 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004874 }
4875
Robert Greenwalt9258c642014-03-26 16:47:06 -07004876 // notify only this one new request of the current state
4877 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4878 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4879 // TODO - read state from monitor to decide what to send.
4880// if (nai.networkMonitor.isLingering()) {
4881// notifyType = NetworkCallbacks.LOSING;
4882// } else if (nai.networkMonitor.isEvaluating()) {
4883// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4884// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004885 if (nri.mPendingIntent == null) {
4886 callCallbackForRequest(nri, nai, notifyType);
4887 } else {
4888 sendPendingIntentForRequest(nri, nai, notifyType);
4889 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004890 }
4891
Robert Greenwalt8d482522015-06-24 13:23:42 -07004892 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004893 // The NetworkInfo we actually send out has no bearing on the real
4894 // state of affairs. For example, if the default connection is mobile,
4895 // and a request for HIPRI has just gone away, we need to pretend that
4896 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4897 // the state to DISCONNECTED, even though the network is of type MOBILE
4898 // and is still connected.
4899 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4900 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004901 if (state != DetailedState.DISCONNECTED) {
4902 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004903 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004904 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004905 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004906 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4907 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4908 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4909 if (info.isFailover()) {
4910 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4911 nai.networkInfo.setFailover(false);
4912 }
4913 if (info.getReason() != null) {
4914 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4915 }
4916 if (info.getExtraInfo() != null) {
4917 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4918 }
4919 NetworkAgentInfo newDefaultAgent = null;
4920 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004921 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004922 if (newDefaultAgent != null) {
4923 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4924 newDefaultAgent.networkInfo);
4925 } else {
4926 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4927 }
4928 }
4929 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4930 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004931 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004932 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004933 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004934 }
4935 }
4936 }
4937
Robert Greenwalt7b816022014-04-18 15:25:25 -07004938 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004939 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004940 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004941 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4942 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4943 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004944 if (nri.mPendingIntent == null) {
4945 callCallbackForRequest(nri, networkAgent, notifyType);
4946 } else {
4947 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4948 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004949 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004950 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004951
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004952 private String notifyTypeToName(int notifyType) {
4953 switch (notifyType) {
4954 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4955 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4956 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4957 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4958 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4959 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4960 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4961 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4962 }
4963 return "UNKNOWN";
4964 }
4965
Jeff Sharkey69736342014-12-08 14:50:12 -08004966 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004967 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
4968 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08004969 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004970 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08004971 try {
4972 mStatsService.forceUpdateIfaces();
4973 } catch (Exception ignored) {
4974 }
4975 }
4976
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004977 @Override
4978 public boolean addVpnAddress(String address, int prefixLength) {
4979 throwIfLockdownEnabled();
4980 int user = UserHandle.getUserId(Binder.getCallingUid());
4981 synchronized (mVpns) {
4982 return mVpns.get(user).addAddress(address, prefixLength);
4983 }
4984 }
4985
4986 @Override
4987 public boolean removeVpnAddress(String address, int prefixLength) {
4988 throwIfLockdownEnabled();
4989 int user = UserHandle.getUserId(Binder.getCallingUid());
4990 synchronized (mVpns) {
4991 return mVpns.get(user).removeAddress(address, prefixLength);
4992 }
4993 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004994
4995 @Override
4996 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4997 throwIfLockdownEnabled();
4998 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004999 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005000 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005001 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005002 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005003 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005004 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005005 }
5006 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005007 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005008
5009 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005010 public String getCaptivePortalServerUrl() {
5011 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5012 }
5013
5014 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005015 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5016 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5017 enforceKeepalivePermission();
5018 mKeepaliveTracker.startNattKeepalive(
5019 getNetworkAgentInfoForNetwork(network),
5020 intervalSeconds, messenger, binder,
5021 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5022 }
5023
5024 @Override
5025 public void stopKeepalive(Network network, int slot) {
5026 mHandler.sendMessage(mHandler.obtainMessage(
5027 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5028 }
5029
5030 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005031 public void factoryReset() {
5032 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005033
5034 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5035 return;
5036 }
5037
Robin Lee3b3dd942015-05-12 18:14:58 +01005038 final int userId = UserHandle.getCallingUserId();
5039
Stuart Scottf1fb3972015-04-02 18:00:02 -07005040 // Turn airplane mode off
5041 setAirplaneMode(false);
5042
Stuart Scotte3e314d2015-04-20 14:07:45 -07005043 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5044 // Untether
5045 for (String tether : getTetheredIfaces()) {
5046 untether(tether);
5047 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005048 }
5049
Stuart Scotte3e314d2015-04-20 14:07:45 -07005050 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
5051 // Turn VPN off
5052 VpnConfig vpnConfig = getVpnConfig(userId);
5053 if (vpnConfig != null) {
5054 if (vpnConfig.legacy) {
5055 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5056 } else {
5057 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5058 // in the future without user intervention.
5059 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005060
Stuart Scotte3e314d2015-04-20 14:07:45 -07005061 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
5062 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005063 }
5064 }
5065 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005066
5067 @VisibleForTesting
5068 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5069 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5070 return new NetworkMonitor(context, handler, nai, defaultRequest);
5071 }
Erik Kline48f12f22016-04-14 17:30:59 +09005072
Hugo Benichi5f16f762016-04-20 12:09:33 +09005073 private static void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
5074 int newNetid = NETID_UNSET;
5075 int prevNetid = NETID_UNSET;
5076 int[] transports = new int[0];
5077 boolean hadIPv4 = false;
5078 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005079
Hugo Benichi5f16f762016-04-20 12:09:33 +09005080 if (newNai != null) {
5081 newNetid = newNai.network.netId;
5082 transports = newNai.networkCapabilities.getTransportTypes();
5083 }
5084 if (prevNai != null) {
5085 prevNetid = prevNai.network.netId;
5086 final LinkProperties lp = prevNai.linkProperties;
5087 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5088 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5089 }
5090
5091 DefaultNetworkEvent.logEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6);
Erik Kline48f12f22016-04-14 17:30:59 +09005092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005093}